# -*- coding: utf-8 mode: python -*- vim:sw=4:sts=4:et:ai:si:sta:fenc=utf-8

__all__ = ('Server',)

try: True, False
except: True, False = 1, 0

from ulib.web import web, Application, Page, defaults
from ulib.tasks import factories, TasksCtl

class Server(Application):
    PORT = 1975

    _ctl = None
    _stores = None
    def get_stores(self):
        stores = self._stores
        if stores is not None: return stores
        else: return self._ctl.get_stores()
    stores = property(get_stores)

    def __init__(self, basedir=None, templatedir=None, host=None, port=None, debug=None,
                 tsrc=None, ctl=None):
        Application.__init__(self, basedir, templatedir, host, port, debug)

        if ctl is None: ctl = TasksCtl(tsrc)
        self._ctl = ctl
        self.OPTIONS = self._ctl.OPTIONS
        self.LONG_OPTIONS = self._ctl.LONG_OPTIONS

    def is_option(self, option, value):
        return self._ctl.is_option(option, value)

    def process_args(self, args):
        if args: self._stores = factories.get_store(args)

class index(Page):
    PREFIX = r'/'

    def index(self):
        return self.render(self.app.stores.get_stores())

    def utf8plaintext(self, text):
        web.header("Content-Type", "text/plain; charset=utf-8", True)
        return text.encode("utf-8")

    def list(self):
        lines = []
        for store in self.app.stores.get_stores():
            lines.append(u"%s:%s" % (store.sid, store.name))
        return self.utf8plaintext(u"\n".join(lines))

    @defaults(sid=None)
    def head(self):
        store = self.app.stores.get_store_by_sid(self.sid)
        if store is None: return self.error()
        else: return self.utf8plaintext(u"\n".join(store.get_hlines()))

    @defaults(sid=None)
    def get(self):
        store = self.app.stores.get_store_by_sid(self.sid)
        if store is None: return self.error()
        else: return self.utf8plaintext(u"\n".join(store.get_lines()))

if __name__ == '__main__':
    import sys
    from os import path

    basedir = path.abspath(path.split(__file__)[0])
    Server(basedir).run(sys.argv[1:])
