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

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

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

    return user1

def create_formdef():
    FormDef.wipe()
    formdef = FormDef()
    formdef.name = 'test'
    formdef.fields = []
    formdef.store()
    return formdef

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

def test_with_user():
    user = create_user()
    app = login(get_app(pub), username='user', password='user')
    resp = app.get('/', status=200)
    resp = app.get('/myspace/', status=200)

def test_myspace_with_user_forms():
    user = create_user()
    formdef = create_formdef()

    cat = Category(name='cat')
    cat.store()
    formdef.category_id = cat.id
    formdef.enable_tracking_codes = True

    wf = Workflow(name='status')
    st1 = wf.add_status('Status1', 'st1')
    wf.store()
    formdef.workflow_id = wf.id
    formdef.store()

    formdef.data_class().wipe()
    formdata = formdef.data_class()()
    formdata.user_id = user.id
    formdata.status = 'wf-st1'
    formdata.data = {}
    formdata.store()
    draft = formdef.data_class()()
    draft.user_id = user.id
    draft.status = 'draft'
    draft.data = {}
    draft.store()

    app = login(get_app(pub), username='user', password='user')
    resp = app.get('/myspace/')
    assert 'Status1' in resp
    assert '<a href="/cat/test/%s/"' % formdata.id in resp
    assert 'Draft' in resp
    assert '<a href="/cat/test/%s"' % draft.id in resp
    resp = app.get('/cat/test/%s' % formdata.id)
    resp.status_int = 200
    resp = app.get('/cat/test/%s' % draft.id, status=302)
    resp = resp.follow(status=302)
    resp.location.startswith('http://example.net/cat/test/?mt=')
    resp = resp.follow(status=200)

    # disable formdef: formdatas are still visible and accessible, drafts are not
    formdef.disabled = True
    formdef.store()
    resp = app.get('/myspace/')
    assert 'Status1' in resp
    assert '<a href="/cat/test/%s/"' % formdata.id in resp
    assert not 'Draft' in resp
    assert not '<a href="/cat/test/%s"' % draft.id in resp
    resp = app.get('/cat/test/%s' % formdata.id)
    resp.status_int = 200
    resp = app.get('/cat/test/%s' % draft.id, status=302)
    resp = resp.follow(status=302)
    resp.location.startswith('http://example.net/cat/test/?mt=')
    resp = resp.follow(status=403)

def test_announces():
    from modules.announces import Announce, AnnounceSubscription

    if not 'misc' in pub.cfg:
        pub.cfg['misc'] = {}
    pub.cfg['misc']['announce_themes'] = ['Foo', 'Bar']
    pub.write_cfg()

    announce = Announce()
    announce.title = 'Hello World'
    announce.text = 'Lorem ipsum...'
    announce.publication_time = time.gmtime(time.time()-100000)
    announce.store()

    user = create_user()
    app = login(get_app(pub), username='user', password='user')
    resp = app.get('/announces/', status=200)
    resp = resp.click('Receiving those Announces')
    resp = resp.click('Email')
    assert 'You are logged in but there is no email address in your profile.' in resp.body
    assert 'email' in resp.form.fields
    user.email = 'foo@localhost'
    user.store()
    resp = app.get('/announces/email', status=200)
    assert 'foo@localhost' in resp.body
    assert not 'email' in resp.form.fields
    resp = resp.form.submit()
    assert AnnounceSubscription.count() == 1

    resp = app.get('/myspace/', status=200)
    resp = resp.click('Edit my Subscription to Announces')
    assert resp.form['themes$elementFoo'].checked
    assert resp.form['themes$elementBar'].checked
    resp.form['themes$elementFoo'].checked = False
    resp = resp.form.submit('submit')
    assert AnnounceSubscription.count() == 1

    resp = app.get('/myspace/announces', status=200)
    assert not resp.form['themes$elementFoo'].checked
    assert resp.form['themes$elementBar'].checked

def test_agenda():
    from modules.events import Event, RemoteCalendar

    remote_calendar = RemoteCalendar()
    remote_calendar.label = 'Remote'
    remote_calendar.store()

    event = Event()
    event.title = 'Hello World'
    event.description = 'Lorem ipsum...'
    event.date_start = time.strptime('2016-09-10', '%Y-%m-%d')
    event.date_end = time.strptime('2016-09-12', '%Y-%m-%d')
    event.store()

    app = get_app(pub)
    resp = app.get('/agenda/', status=200)
    resp = app.get('/agenda/filter')
    assert 'tags$element0' in resp.form.fields
    assert 'calendars$element0' in resp.form.fields

def test_form_category_redirection():
    Category.wipe()
    cat = Category(name='baz')
    cat.store()

    FormDef.wipe()
    formdef = FormDef()
    formdef.name = 'foobar'
    formdef.category_id = cat.id
    formdef.fields = []
    formdef.store()

    # check we get a redirection to /category/formdef/
    resp = get_app(pub).get('/foobar/')
    assert resp.location.endswith('/baz/foobar/')

def test_form_and_category_same_slug():
    Category.wipe()
    cat = Category(name='foobar')
    cat.store()

    FormDef.wipe()
    formdef = FormDef()
    formdef.name = 'foobar'
    formdef.category_id = cat.id
    formdef.fields = []
    formdef.store()

    # check we get to the form, not the category
    resp = get_app(pub).get('/foobar/')
    assert resp.form
