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

import yurlungur
from yurlungur.core import logger


def cache(func, *args, **kwargs):
    saved = {}

    @functools.wraps(func)
    def wrapper(*args):
        if args in saved:
            return saved[args]
        result = func(*args)
        saved[args] = result
        return result

    return wrapper if sys.version_info < (3, 2) else functools.lcu_cache(*args, **kwargs)


def trace(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except:
            if hasattr(logger.logger, "warn"):
                logger.logger.warn(traceback.format_exc())
            else:
                logger.logger.log(traceback.format_exc(), logger.Warning)

    return wrapper


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

    return wrapper


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 __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, **kwargsargs):\n".format(fn))
            f.write("   \"\"\"{0}\"\"\"\n".format(inspect.getdoc(fn)))
            f.write("   pass\n\n")

    # return inspect.getmembers(__import__(completer))
