#!/usr/bin/python
import os
from amplee.loader import loader
import amplee.atompub.member.atom

base_dir = os.getcwd()
def setup_store():
    return loader(os.path.join(base_dir, 'amplee.conf'),
                           encoding='UTF-8', base_path=base_dir)

from amplee.handler.store.cp import Service, Store
import cherrypy

class Null(object):
    pass

def setup_apps():
    service, conf = setup_store()
    workspace = service.get_workspace('commits')
    
    travis = Null()
    travis.service = Service(service)
    commits = Null()
    travis.commits = commits

    cosmo = workspace.get_collection('cosmo')
    commits.cosmo = Store(cosmo, strict=True)

    testing = workspace.get_collection('testing')
    commits.testing = Store(testing, strict=True)
    return travis, conf

def setup_server():
    app, config = setup_apps()

    method_dispatcher = cherrypy.dispatch.MethodDispatcher()
    conf = {'/': {'tools.etags.on': True,
                  'tools.etags.autotags': False,
                  'request.dispatch': method_dispatcher
                  },
            '/static': {'tools.staticdir.on': True,
                        'tools.staticdir.dir': os.path.join(base_dir, 'static')},
            '/commits/cosmo': {'request.dispatch': method_dispatcher,}
            }

    server_conf = {'global': {'server.socket_port': 8000,
                              'server.socket_host': '127.0.0.1',
                              'tools.proxy.on': True,
                              'tools.proxy.base': 'tvachon.info',
                              'log.screen': True,
                              'log.error_file': os.path.join(base_dir, 'logs', "error.log"),
                              'log.access_file': os.path.join(base_dir, 'logs', "access.log"),
                              #'error_page.404': os.path.join(base_dir, 'static', 'notfound.html'),
                              'request.show_tracebacks': True}}
    cherrypy.config.update(server_conf)

    # If you change the script_name here, you will have to update the css too
    # and update the different URLs
    cherrypy.tree.mount(app, '/', config=conf)
    cherrypy.server.quickstart()
    cherrypy.engine.start()
    
if __name__ == '__main__':
    setup_server()
