import ConfigParser
import os
import tempfile

from webtest import TestApp
from quixote import cleanup, get_publisher
from django.conf import settings

from wcs.qommon.publisher import set_publisher_class
import wcs
import wcs.wsgi
from wcs.qommon.http_request import HTTPRequest
from wcs import publisher, compat

import wcs.middleware

wcs.middleware.AfterJobsMiddleware.ASYNC = False

def create_temporary_pub():
    config = ConfigParser.ConfigParser()
    APP_DIR = tempfile.mkdtemp()
    compat.CompatWcsPublisher.APP_DIR = APP_DIR
    compat.CompatWcsPublisher.DATA_DIR = os.path.abspath(
            os.path.join(os.path.dirname(wcs.__file__), '..', 'data'))
    compat.CompatWcsPublisher.cronjobs = None
    config.add_section('extra')
    config.set('extra', 'auquotidien', os.path.join(os.path.dirname(__file__), '..', 'auquotidien'))
    compat.CompatWcsPublisher._initialized = False
    compat.CompatWcsPublisher.configure(config)
    compat.CompatWcsPublisher.init_publisher_class()
    pub = compat.CompatWcsPublisher.create_publisher()
    # allow saving the user
    pub.app_dir = os.path.join(APP_DIR, 'example.net')
    os.mkdir(pub.app_dir)
    return pub

def get_app(pub, https=False):
    extra_environ = {'HTTP_HOST': 'example.net', 'REMOTE_ADDR': '127.0.0.1'}
    if https:
        settings.SECURE_PROXY_SSL_HEADER = ('HTTPS', 'on')
        extra_environ['HTTPS'] = 'on'
    else:
        extra_environ['HTTPS'] = 'off'
    return TestApp(wcs.wsgi.application, extra_environ=extra_environ)

def login(app, username='admin', password='admin'):
    login_page = app.get('/login/')
    login_form = login_page.forms['login-form']
    login_form['username'] = username
    login_form['password'] = password
    resp = login_form.submit()
    assert resp.status_int == 302
    return app
