"""Pylons application test package

This package assumes the Pylons environment is already loaded, such as
when this script is imported from the `nosetests --with-pylons=test.ini`
command.

This module initializes the application via ``websetup`` (`paster
setup-app`) and provides the base testing objects.
"""
from unittest import TestCase

from paste.deploy import loadapp
from paste.script.appinstall import SetupCommand
from pylons import config, url
from routes.util import URLGenerator
from webtest import TestApp
from {{package}}.model import *
from {{package}}.model.meta import Session
import {{package}}.model as model
from {{package}}.lib import chomsky
from elixir import *
import sqlalchemy
import os
import datetime
import hashlib
import pylons.test

__all__ = ['environ', 'url', 'TestController', 'TestAuthenticatedController', 'TestModel']

# Invoke websetup with the current config file
# SetupCommand('setup-app').run([config['__file__']])

# additional imports ...
from paste.deploy import appconfig
from {{package}}.config.environment import load_environment

here_dir = os.path.dirname(__file__)
conf_dir = os.path.dirname(os.path.dirname(here_dir))

test_file = os.path.join(conf_dir, 'test.ini')
conf = appconfig('config:' + test_file)
load_environment(conf.global_conf, conf.local_conf)
environ = {}


engine = sqlalchemy.engine_from_config(config, 'sqlalchemy.')
metadata = elixir.metadata
Session = elixir.session = meta.Session

class TestModel(TestCase):
    
    def setUp(self):
        elixir.session.configure(bind=engine)
        metadata.create_all(engine)
        perm = Permission(id=1,
                          name = u"Editors",
                          description = u"Can edit content.")
        Session.add(perm)
        gadmin = Group(id=1,
                       name = u"Administrators",
                       description = u"Administration group",
                       created = datetime.datetime.utcnow(),
                       active = True)
        Session.add(gadmin)
        g = Session.query(Group).filter_by(
                    name=u"Administrators").all()
        assert len(g) == 1
        assert g[0] == gadmin
        admin = User(id=1,
                     username = u"admin", 
                     password=hashlib.sha1("admin").hexdigest(),
                     password_check=hashlib.sha1("admin").hexdigest(), 
                     email="admin@example.com",
                     created = datetime.datetime.utcnow(),
                     active = True)
        gadmin.users.append(admin)
        gadmin.permissions.append(perm)
        Session.add(admin)
        ce = ChangelogItem(content=admin.username,
                           user=admin,
                           refid=admin.id, 
                           action=u'add')
        Session.add(ce)
        u = Session.query(User).filter_by(username=u"admin").all()
        assert len(u) == 1
        assert u[0] == admin

        user = User(id=2,
                     username = u"test", 
                     password=hashlib.sha1("test").hexdigest(),
                     password_check=hashlib.sha1("test").hexdigest(), 
                     email="test@example.com",
                     created = datetime.datetime.utcnow(),
                     active = True)
        assert user.username == u'test'
        Session.add(user)
        group = Group(id=2, name = u'Subscription Members')
        Session.add(group)
        assert group.name == u'Subscription Members'
        group.permissions.append(Permission(id=2,name = u'add_users'))
        assert len(group.permissions) == 1
        Session.add(group)
        u = Session.query(User).all()
        assert len(u) == 2
        home = Page(id=1,
                    title = u"msite home page",
                    content = u''.join(['<p>%s</p>' % chomsky.chomsky(times=x) for x in range(1,4)]),
                    slug = 'home', 
                    published = datetime.datetime.utcnow(),
                    author = admin,
                    display = True)
        Session.add(home)
        about = Page(id=2,
                     title = u"About msite",
                     content = u''.join(['<p>%s</p>' % chomsky.chomsky(times=x) for x in range(1,4)]),
                     slug = 'about', 
                     published = datetime.datetime.utcnow(),
                     author = admin,
                     display = True)
        Session.add(about)
        pgs = Session.query(Page).all()
        assert len(pgs) == 2
        Session.commit()
    
    def tearDown(self):
        metadata.drop_all(engine)
    

class TestController(TestModel):
    
    def __init__(self, *args, **kwargs):
        if pylons.test.pylonsapp:
            wsgiapp = pylons.test.pylonsapp
        else:
            wsgiapp = loadapp('config:%s' % config['__file__'])
        self.app = TestApp(wsgiapp)
        url._push_object(URLGenerator(config['routes.map'], environ))
        TestCase.__init__(self, *args, **kwargs)
    

class TestAuthenticatedController(TestModel):
    
    def __init__(self, *args, **kwargs):
        if pylons.test.pylonsapp:
            wsgiapp = pylons.test.pylonsapp
        else:
            wsgiapp = loadapp('config:%s' % config['__file__'])
        self.app = TestApp(wsgiapp, extra_environ=dict(REMOTE_USER='admin'))
        url._push_object(URLGenerator(config['routes.map'], environ))
        TestCase.__init__(self, *args, **kwargs)
    

