import pytest

from wcs.qommon.http_request import HTTPRequest
from wcs.carddef import CardDef
from wcs.fields import StringField

from utilities import create_temporary_pub, clean_temporary_pub

def pytest_generate_tests(metafunc):
    if 'pub' in metafunc.fixturenames:
        metafunc.parametrize('pub', ['pickle', 'sql'], indirect=True)

@pytest.fixture
def pub(request):
    pub = create_temporary_pub(sql_mode=(request.param == 'sql'))
    req = HTTPRequest(None, {'SCRIPT_NAME': '/', 'SERVER_NAME': 'example.net'})
    pub.set_app_dir(req)
    pub.cfg['language'] = {'language': 'en'}
    pub.write_cfg()
    return pub

def teardown_module(module):
    clean_temporary_pub()


def test_basics(pub):
    carddef = CardDef()
    carddef.name = 'foo'
    carddef.fields = [
        StringField(id='1', label='Test', type='string', varname='foo'),
    ]
    carddef.store()
    assert CardDef.get(carddef.id).name == 'foo'

    carddata_class = carddef.data_class()
    carddata = carddata_class()
    carddata.data = {'1': 'hello world'}
    carddata.just_created()
    carddata.store()
    assert carddata.status == 'wf-recorded'

    assert carddata_class.get(carddata.id).data['1'] == 'hello world'
    assert carddata_class.get(carddata.id).status == 'wf-recorded'

def test_xml_export_import(pub):
    carddef = CardDef()
    carddef.name = 'foo'
    carddef.fields = [
        StringField(id='1', label='Test', type='string', varname='foo'),
    ]
    carddef.store()
    carddef_xml = carddef.export_to_xml()
    assert carddef_xml.tag == 'carddef'

    carddef2 = CardDef.import_from_xml_tree(carddef_xml)
    assert carddef2.name == 'foo'
