# -*- coding: utf-8 -*-
import sys
import os
import traceback
import functools
import time
import inspect
import sqlite3


def __db_loader():
    from collections import namedtuple

    local = os.path.dirname(os.path.dirname(inspect.currentframe().f_code.co_filename))
    cache = os.path.join(local, "user", "cache.db").replace(os.sep, "/")

    conn = sqlite3.connect(cache)
    c = conn.cursor()
    for row in c.execute('SELECT * FROM stocks ORDER BY price'):
        print(row)

    return namedtuple


def __db_attr():
    local = os.path.dirname(os.path.dirname(inspect.currentframe().f_code.co_filename))
    cache = os.path.join(local, "user", "cache.db").replace(os.sep, "/")

    conn = sqlite3.connect(cache)
    c = conn.cursor()
    c.execute('''CREATE TABLE stocks
                 (date text, trans text, symbol text, qty real, price real)''')
    c.execute("INSERT INTO stocks VALUES ('2006-01-05','BUY','RHAT',100,35.14)")
    conn.commit()
    conn.close()


def __import__(name, globals=None, locals=None, fromlist=None):
    # Fast path: see if the module has already been imported.
    try:
        return sys.modules[name]
    except KeyError:
        pass

    try:
        import imp
    except:
        from importlib import import_module
        return import_module(name)

    fp, pathname, description = imp.find_module(name)
    try:
        return imp.load_module(name, fp, pathname, description)
    finally:
        if fp:
            fp.close()


def __make_completer(mod):
    local = os.path.dirname(os.path.dirname(inspect.currentframe().f_code.co_filename))
    completer = os.path.join(local, "user", "completer.pyi").replace(os.sep, "/")

    header = "\"\"\"this document generated by internal module.\"\"\"\n\n\n"
    module = __import__(mod)
    with open(completer, "w") as f:
        f.write(header)

        for fn, _ in inspect.getmembers(module):
            if fn.startswith("_"):
                continue

            f.write("def {0}(*args, **kwargs):\n".format(fn))
            f.write("   \"\"\"{0}\"\"\"\n".format(inspect.getdoc(fn)))
            f.write("   pass\n\n")

    # return inspect.getmembers(__import__(completer))


def __dark_view(view):
    local = os.path.dirname(
        os.path.dirname(inspect.currentframe().f_code.co_filename)
    )
    with open(local + "/user/dark.css") as f:
        view.setStyleSheet("".join(f.readlines()))


def analyze(func):
    @functools.wraps(func)
    def Wrapper(*args, **kw):
        try:
            ret = func(*args, **kw)
            return ret
        except:
            print(traceback.format_exc())
        return

    return Wrapper


def timer(func):
    @functools.wraps(func)
    def Wrapper(*args, **kw):
        print('{0} start'.format(func.__name__))
        start_time = time.clock()
        ret = func(*args, **kw)
        end_time = time.clock()
        print('\n{0}: {1:,f}s'.format("total: ", (end_time - start_time)))
        return ret

    return Wrapper


try:
    from yurlungur.Qt.QtCore import *
    from yurlungur.Qt.QtGui import *
    from yurlungur.Qt.QtWidgets import *
except ImportError:
    pass


class __GCProtector(object):
    widgets = []


def max_protect_window(w):
    w.setWindowFlags(Qt.WindowStaysOnTopHint)
    w.show()
    __GCProtector.widgets.append(w)


def qmain_window():
    import yurlungur.core.app
    app_name = yurlungur.core.application.__name__

    if app_name == "maya.cmds":
        from yurlungur.Qt import QtCompat
        from maya import OpenMayaUI
        ptr = long(OpenMayaUI.MQtUtil.mainWindow())
        return QtCompat.wrapInstance(ptr, QWidget)

    if app_name == "pymxs":
        import MaxPlus
        return MaxPlus.QtHelpers_GetQmaxMainWindow()
        # MaxPlus.NotifyQWidgetModalityChange(w, false)
        # MaxPlus.MakeQWidgetDockable(w, 14)

    if app_name == "hou":
        import hou
        return hou.qt.mainWindow()

    return None


def show(view):
    try:
        view.deleteLater()
    except:
        pass

    try:
        view.show()
    except:
        view.deleteLater()
        traceback.print_exc()

    if not QApplication.instance():
        app = QApplication(sys.argv)
        __dark_view(view)
        view.show()
        sys.exit(app.exec_())
