import os, cStringIO

from Ft.Lib.CommandLine import CommandLineTestUtil

import test_prime
from Ft.Server.Client import Core
from Ft.Server.Client.Commands import CommandUtil

def Init(repo):
    if repo.hasResource(FIRST_RAWFILE):
        repo.deleteResource(FIRST_RAWFILE)
    rf = repo.createRawFile(FIRST_RAWFILE,'text/text',RAW1)
    if repo.hasResource(FIRST_ALIAS):
        repo.deleteResource(FIRST_ALIAS,traverseAliases = 0)
    rf.addAlias(FIRST_ALIAS)

FIRST_RAWFILE = '/' + test_prime.BASE_CONTAINER + '/rf1'
FIRST_ALIAS = '/' + test_prime.BASE_CONTAINER + '/rfa1'


def Test(tester):

    test_prime.InitRepo(tester,Init,['4ss','fetch','rawfile'])

    baseConfig = {'host':tester.test_data['ftrpc-host'],
                  'port':tester.test_data['ftrpc-port'],
                  'username':tester.test_data['userName'],
                  'password':tester.test_data['password'],
                  }

    #Fetch the RF
    expected = MakeExpected(FIRST_RAWFILE, RAW1)
    tr1 = CommandLineTestUtil.TestRun('Basic Fetch',
                                      baseConfig,
                                      [FIRST_RAWFILE],
                                      expectedOut=expected)

    expected = MakeExpected(FIRST_ALIAS, RAW1)
    tr2 = CommandLineTestUtil.TestRun('Basic Fetch of Alias',
                                      baseConfig,
                                      [FIRST_ALIAS],
                                      expectedOut=expected)

    #Fetch an unknown rf
    uri = '/' + test_prime.BASE_CONTAINER + '/foo'
    tr3 = CommandLineTestUtil.TestRun('Error Fetch',
                                      baseConfig,
                                      [uri],
                                      expectedOut=expected_2%uri)


    t = CommandLineTestUtil.Test('4ss fetch rawfile',[tr1,tr2,tr3])

    return t.test(tester)

import test_create_raw_file
RAW1 = test_create_raw_file.RAW1

def MakeExpected(path, content):
    sio = cStringIO.StringIO()
    CommandUtil.WritePreamble("Raw File %s (text/text):" % path, stream=sio)
    sio.write(content)
    sio.write('\n')
    return sio.getvalue()

expected_2 = "Path %s is unknown\n"
