import datetime
import os
import random
import shutil
import sys
import time

import pytest

from quixote import cleanup

from wcs import publisher
from wcs import fields

from utilities import create_temporary_pub


def setup_module(module):
    cleanup()
    global pub
    pub = create_temporary_pub()


def teardown_module(module):
    shutil.rmtree(pub.APP_DIR)


def test_get_users_with_name_identifier():
    pub.user_class.wipe()

    user = pub.user_class()
    user.name = 'Pierre'
    user.name_identifiers = ['foo']
    user.store()
    user_id = user.id

    user = pub.user_class()
    user.name = 'Papier'
    user.store()

    assert len(pub.user_class.get_users_with_name_identifier('foo')) == 1
    assert pub.user_class.get_users_with_name_identifier('foo')[0].name == 'Pierre'


def test_get_users_with_role():
    pub.user_class.wipe()

    user = pub.user_class()
    user.name = 'Pierre'
    user.roles = [1]
    user.store()
    user_id = user.id

    user = pub.user_class()
    user.name = 'Papier'
    user.store()

    assert len(pub.user_class.get_users_with_role(1)) == 1
    assert pub.user_class.get_users_with_role(1)[0].name == 'Pierre'

def test_user_formdef_getattr():
    from wcs.admin.settings import UserFieldsFormDef
    formdef = UserFieldsFormDef(pub)
    formdef.fields = [
        fields.StringField(id='3', label='test', type='string', varname='plop'),
        fields.StringField(id='9', label='noop', type='string', varname='get_formdef'),
    ]
    formdef.store()

    user = pub.user_class()
    assert user.plop is None
    assert user.get_formdef()  # get_formdef is not overrided by varname "get_formdef" 

    user.form_data = {'3': 'Bar', '9': 'Foo'}
    assert user.plop == 'Bar'
    assert user.get_formdef != 'Foo'

    with pytest.raises(AttributeError):
        user.xxx
