#!/usr/bin/env python
# -*- coding: utf-8 -*-


"""

Auteur :      thuban <thuban@yeuxdelibad.net>
licence :     MIT

Description : dontpanic-server starter

"""

import bottle
import logging
import os
import sys

from argparse import ArgumentParser

from dontpanic.ui import DontPanic
from dontpanic.i18nlib import _
from dontpanic.utils import setup_logging, progname, progversion

serverlist = ["cgi", "paste", "cherrypy", "tornado", "auto"]
logger = logging.getLogger(__name__)


class ServerParser(ArgumentParser):
    def error(self, message):
        sys.stderr.write('error: %s\n' % message)
        self.print_help()
        sys.exit(2)


class DontpanicCGI(DontPanic):
    def __init__(self, host, port, admin, adminpw):
        DontPanic.__init__(self, host, port, admin, adminpw, local_=False)
        self.app = bottle.default_app()

    def run(self):
        logger.info("running on {}:{}".format(self.host, self.port))
        self.app.run(server='cgi')


class DontpanicAdapter(DontPanic):
    # require python-cherrypy3
    # or
    # python-paste
    def __init__(self, host, port, admin, adminpw, adapter):
        self.adapter = adapter
        DontPanic.__init__(self, host, port, admin, adminpw, local_=False)

    def run(self):
        logger.info("running on {}:{}".format(self.host, self.port))
        self.app.run(host=self.host, port=self.port, server=self.adapter)


if __name__ == '__main__':
    parser = ServerParser(prog=progname, description=_("Dontpanic is a python app to look for any movie or "
                                                       "serie and watch them in streaming. You can deploy it on your "
                                                       "server and make it available for the world."))

    parser.add_argument("-v", "--verbose", action="count", default=0, help=_("Increase output verbosity"))
    parser.add_argument("--version", action="version", version=progversion, help=_("Print version"))

    parser.add_argument("adapter", choices=serverlist, help=_("The adapter to use"))
    parser.add_argument("admin", help=_("Admin user name"))
    parser.add_argument("password", help=_("Admin password"))
    parser.add_argument("port", help=_("Which port Don't Panic will listen"))

    args = parser.parse_args()

    setup_logging(args.verbose)

    os.chdir(os.path.dirname(os.path.abspath(__file__)))
    option = args.adapter
    host = "0.0.0.0"
    admin = args.admin
    adminpw = args.password
    port = args.port
    if option == "-cgi":
        dnp = DontpanicCGI(host, port, admin=admin, adminpw=adminpw)
        dnp.run()
    elif option == "-cherrypy" or option == "-paste" or option == "-auto":
        dnp = DontpanicAdapter(host, port, admin=admin, adminpw=adminpw, adapter=option.replace('-', '', 1))
        dnp.run()
    else:
        try:
            dnp = DontpanicAdapter(host, port, admin=admin, adminpw=adminpw, adapter=option.replace('-', '', 1))
            dnp.run()
        except Exception as e:
            print(e)
            parser.print_help()

# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
