import os, cStringIO
from Ft.Lib.CommandLine import CommandLineTestUtil
import tempfile


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

FIRST_DOCUMENT = '/' + test_prime.BASE_CONTAINER + '/doc1'
FIRST_DOCUMENT_ALIAS = '/' + test_prime.BASE_CONTAINER + '/doca1'

def Init(repo):
    if repo.hasResource(FIRST_DOCUMENT):
        repo.deleteResource(FIRST_DOCUMENT)
    if repo.hasResource(FIRST_DOCUMENT_ALIAS):
        repo.deleteResource(FIRST_DOCUMENT_ALIAS,traverseAliases = 0)
    doc = repo.createDocument(FIRST_DOCUMENT,DOC1)
    doc.addAlias(FIRST_DOCUMENT_ALIAS)

def Test(tester):

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

    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 DOC
    expected = MakeExpected(FIRST_DOCUMENT, DOC1)
    tr1 = CommandLineTestUtil.TestRun('Basic Fetch',
                                      baseConfig,
                                      [FIRST_DOCUMENT],
                                      expectedOut=expected)

    config = baseConfig.copy()
    config['quiet'] = None
    tr2 = CommandLineTestUtil.TestRun('Basic Fetch Alias',
                                      config,
                                      [FIRST_DOCUMENT_ALIAS],
                                      DOC1)

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


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

    return t.test(tester)

import test_create_document
DOC1 = test_create_document.DOC1

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

expected_2 = "Path %s is unknown\n"
