import os
import shutil
import StringIO
import time

try:
    import lasso
except ImportError:
    lasso = None

import pytest

from quixote import cleanup, get_publisher
from wcs.qommon import errors, sessions
from wcs.qommon.ident.password_accounts import PasswordAccount
from wcs.qommon.http_request import HTTPRequest
from wcs.qommon.template import get_current_theme
from wcs.categories import Category
from wcs.roles import Role
from wcs.workflows import Workflow
from wcs.formdef import FormDef
from wcs import fields

from utilities import get_app, login, create_temporary_pub

def setup_module(module):
    cleanup()

    global pub

    pub = create_temporary_pub()

    req = HTTPRequest(None, {'SCRIPT_NAME': '/', 'SERVER_NAME': 'example.net'})
    pub.set_app_dir(req)
    pub.cfg['identification'] = {'methods': ['password']}
    pub.write_cfg()

def create_superuser():
    global user1
    if pub.user_class.has_key('admin'):
        user1 = pub.user_class.get('admin')
        user1.is_admin = True
        user1.roles = []
        return
    user1 = pub.user_class(name='admin')
    user1.id = 'admin'
    user1.is_admin = True
    user1.roles = []
    user1.store()

    account1 = PasswordAccount(id='admin')
    account1.set_password('admin')
    account1.user_id = user1.id
    account1.store()

    pub.cfg['identification'] = {'methods': ['password']}
    pub.write_cfg()

def create_role():
    Role.wipe()
    role = Role(name='foobar')
    role.store()
    return role

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

@pytest.fixture
def empty_siteoptions():
    open(os.path.join(pub.app_dir, 'site-options.cfg'), 'w').close()

def test_with_superuser():
    create_superuser()
    app = login(get_app(pub))
    resp = app.get('/backoffice/')
    # this makes sure the extension loaded properly
    assert '<span id="applabel">Publik</span>' in resp.body

def test_general_admin_permissions():
    create_superuser()
    app = login(get_app(pub))
    resp = app.get('/backoffice/settings/', status=200)
    pub.cfg['admin-permissions'] = {'settings': ['XXX']}
    pub.write_cfg()
    resp = app.get('/backoffice/settings/', status=403)
    user1.roles = ['XXX']
    user1.store()
    resp = app.get('/backoffice/settings/', status=200)
    del pub.cfg['admin-permissions']
    pub.write_cfg()

def test_aq_permissions_panel(empty_siteoptions):
    create_superuser()
    app = login(get_app(pub))
    resp = app.get('/backoffice/settings/')
    assert not 'aq/permissions' in resp.body

    with open(os.path.join(pub.app_dir, 'site-options.cfg'), 'w') as fd:
        if not pub.site_options.has_section('options'):
            pub.site_options.add_section('options')
        pub.site_options.set('options', 'auquotidien-links', 'true')
        pub.site_options.write(fd)

    resp = app.get('/backoffice/settings/')
    assert 'aq/permissions' in resp.body
    resp = app.get('/backoffice/settings/aq/permissions')

def test_menu_items(empty_siteoptions):
    create_superuser()
    role = create_role()

    with open(os.path.join(pub.app_dir, 'site-options.cfg'), 'w') as fd:
        if not pub.site_options.has_section('options'):
            pub.site_options.add_section('options')
        pub.site_options.set('options', 'auquotidien-links', 'true')
        pub.site_options.write(fd)

    for area in ('links', 'announces', 'events', 'links', 'payments'):

        with open(os.path.join(pub.app_dir, 'site-options.cfg'), 'w') as fd:
            if not pub.site_options.has_section('options'):
                pub.site_options.add_section('options')
            pub.site_options.set('options', 'auquotidien-%s' % area, 'true')
            pub.site_options.write(fd)

        pub.cfg['aq-permissions'] = {area: None}
        pub.write_cfg()

        user1.is_admin = True
        user1.roles = []
        user1.store()

        app = login(get_app(pub))
        resp = app.get('/backoffice/')
        assert not '/%s/' % area in resp.body
        resp = app.get('/backoffice/%s/' % area, status=403)

        pub.cfg['aq-permissions'] = {area: 'XXX'}
        pub.write_cfg()

        resp = app.get('/backoffice/')
        assert '/%s/' % area in resp.body
        resp = app.get('/backoffice/%s/' % area, status=200)

        user1.is_admin = False
        user1.roles = [role.id]
        user1.store()
        resp = app.get('/backoffice/')
        assert not '/%s/' % area in resp.body
        resp = app.get('/backoffice/%s/' % area, status=403)

        user1.is_admin = False
        user1.roles = [role.id, 'XXX']
        user1.store()
        resp = app.get('/backoffice/')
        assert '/%s/' % area in resp.body
        resp = app.get('/backoffice/%s/' % area, status=200)
