import os
import shutil
import StringIO
import time

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_agent():
    if pub.user_class.has_key('agent'):
        return
    user1 = pub.user_class(name='agent')
    user1.id = 'admin'
    user1.is_admin = False
    user1.store()

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

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

    return user1

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

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

def test_with_agent():
    user = create_agent()
    app = login(get_app(pub), username='agent', password='agent')
    resp = app.get('/backoffice/', status=403)
    role = create_role()
    user.roles = [role.id]
    user.store()

    app = login(get_app(pub), username='agent', password='agent')
    resp = app.get('/backoffice/')
    # check user is automatically redirected to management/
    assert resp.location == 'http://example.net/backoffice/management/'

def test_with_agent_submitter():
    user = create_agent()
    role = create_role()
    user.roles = [role.id]
    user.store()
    FormDef.wipe()
    formdef = FormDef()
    formdef.name = 'form test'
    formdef.fields = []
    formdef.store()

    app = login(get_app(pub), username='agent', password='agent')
    resp = app.get('/backoffice/')
    # check user is automatically redirected to management/
    assert resp.location == 'http://example.net/backoffice/management/'

    formdef.backoffice_submission_roles = [role.id]
    formdef.store()
    resp = app.get('/backoffice/', status=200) # no redirect
    # check the management and submission links are presend twice, once in the
    # sidebar and once in the page body
    assert resp.body.count('//example.net/backoffice/management/') == 2
    assert resp.body.count('//example.net/backoffice/submission/') == 2

    formdef.backoffice_submission_roles = ['blah']
    formdef.store()
    resp = app.get('/backoffice/')
    # check user is automatically redirected to management/
    assert resp.location == 'http://example.net/backoffice/management/'
