#!/usr/bin/env python

from optparse import OptionParser
import sys
import os

from PyQt5.QtWidgets import QApplication
from PyQt5.QtCore import QFile, QTextStream
from PyQt5.QtGui import QFontDatabase

from ui.panel import Panel
from settings import Settings

import logging
from logging.handlers import RotatingFileHandler
from logging import StreamHandler


USAGE = (""" TODO """)
DESCRIPTION = (""" TODO """)
VERSION = "0.0.1"


def getopts(sys_argv):
    options = None

    parser = OptionParser(usage=USAGE, description=DESCRIPTION)
    parser.add_option("-H", "--host", action="store", type="str",
                      help="Database server", default="127.0.0.1")
    parser.add_option("-D", "--db", action="store", type="str",
                      help="Database name")
    parser.add_option("-U", "--user", action="store", type="str",
                      help="Database user", default="l3")
    parser.add_option("-W", "--password", action="store", type="str",
                      help="Database password")
    parser.add_option("-m", "--migrate", action="store_true",
                      help="Migrate models as first", default=False)
    parser.add_option("-p", "--prompt", type=int,
                      help="Open prompt at passed screen", default=0)
    parser.add_option("-l", "--logfile", action="store", type='str',
                      help="Path of logging file", default='/tmp/kumite-app.log')
    parser.add_option("-v", "--version", action="store_true",
                      help="Print version and exit.")

    (options, args) = parser.parse_args()
    return options


def version_exit():
    print("Version %s" % VERSION)
    sys.exit(0)


def init_logging(opts):
    settings = Settings().logging
    fpath = opts.logfile and opts.logfile or settings['path'].get()
    # -- Assure the destination directory exists to avoid start errors
    dpath = os.path.dirname(os.path.realpath(fpath))
    if not os.path.exists(dpath):
        fpath = os.path.join(os.getcwd(), os.path.basename(fpath))
        print("Using new logging path %s" % fpath)
        settings['path'].set(fpath)

    if not fpath or fpath == 'stdout':
        hdl = StreamHandler(stream=sys.stdout)
    else:
        hdl = RotatingFileHandler(fpath, maxBytes=settings['size'].get() * 1024 * 1024,
                                  backupCount=settings['backups'].get())

    fmt = logging.Formatter('%(asctime)s %(name)-12s [%(levelname)-8s] %(message)s',
                            '%Y-%m-%d %H:%M:%S')
    hdl.setFormatter(fmt)

    level = getattr(logging, settings['level'].get())
    logging.basicConfig(level=level, handlers=[hdl])

    logging.getLogger('main').setLevel(level)
    logging.getLogger('main').info('Started logging');
    logging.getLogger('main').info('Settings file %s' % Settings().fileName())


def main(argv):
    opts = getopts(argv)
    init_logging(opts)

    app = QApplication(sys.argv)

    qname = ':resources/stylesheet_nt.qss' if os.name == 'nt' else ':resources/stylesheet_linux.qss'
    qss = QFile(qname)
    qss.open(QFile.OpenModeFlag.ReadOnly)
    app.setStyleSheet(QTextStream(qss).readAll())
    qss.close()

    QFontDatabase.addApplicationFont(":/fonts/Bank_Gothic_Medium_BT.ttf")

    gui = Panel(opts)

    if opts.db:
        gui.load_database(opts.db, opts.migrate)
    if opts.prompt:
        gui.show_prompt(opts.prompt)

    gui.show()
    sys.exit(app.exec_())


if __name__=='__main__':
    main(sys.argv)
