#!/usr/bin/env python
# coding: utf-8
from os.path import dirname, abspath
from sys import path

ROOT = abspath(dirname(__file__))
path.append(ROOT)

import cyclone.web
from twisted.application import service, internet
from twisted.python.logfile import DailyLogFile
from twisted.python.log import ILogObserver, FileLogObserver
from nsimetadataservice.http import HttpHandler
from nsimetadataservice.auth import Authentication
from ConfigParser import RawConfigParser

CONF = '${conf-path}'
DB_FILE = '${db-file}'

SAM_URL = '${sam:url}'
SAM_USER = '${sam:user}'
SAM_PASS = '${sam:pass}'

TASK_QUEUE = '${task_queue}'


def get_authenticator(conf):
    return Authentication(DB_FILE)

class MetadataService(cyclone.web.Application):

    def __init__(self):
        handlers = [
            (r"/", HttpHandler),
        ]

        settings = {
            "auth": get_authenticator(CONF),
            "sam_url": SAM_URL,
            "sam_user": SAM_USER,
            "sam_pass": SAM_PASS,
            "task_queue": TASK_QUEUE,
        }

        cyclone.web.Application.__init__(self, handlers, debug=True, **settings)

logfile = DailyLogFile("metadataservice.log", "${buildout:log-directory}")
application = service.Application("MetadataService")
application.setComponent(ILogObserver, FileLogObserver(logfile).emit)
srv = internet.TCPServer(${port}, MetadataService(), interface='${host}')
srv.setServiceParent(application)
