import os
import csv
import sqlite3
from glob import glob

class DBManager:

    def __init__(self):
        return

    def insert(self, db_filename, hts_dir):
        tableName = 'hts'
        conn = sqlite3.connect(db_filename)
        cursor = conn.cursor()

        # 테이블 생성
        cursor.execute("CREATE TABLE IF NOT EXISTS " + tableName + " (CODE text, NAME text, ymd text, hms text, close REAL, open REAL, high REAL, low REAL, volume REAL, label INTEGER DEFAULT 0)")

        # 키 생성
        create_key = "CREATE INDEX IF NOT EXISTS " + tableName + "_idx on " + tableName + " (CODE, ymd, hms, label) "
        cursor.execute(create_key)

        conn.commit()
        cursor.close()
        conn.close()

        conn = sqlite3.connect(db_filename)
        cursor = conn.cursor()

        fileNames = glob(hts_dir)
        for fileName in fileNames:
            stock_code = None
            stock_name = None
            if fileName.find("252670") >= 0:
                stock_code = "252670"
                stock_name = "KODEX 200선물인버스2X"
            elif fileName.find("122630") >= 0:
                stock_code = "122630"
                stock_name = "KODEX 레버리지"
            if stock_code is None or stock_name is None:
                continue

            infp = open(fileName, 'r', encoding='utf-8')
            reader = csv.reader(infp)
            next(reader)

            for rows in reader:
                ymd = rows[0]  # hts.날짜
                hms = rows[1]  # hts.시간
                open_v = rows[2]  # hts.시가
                high = rows[3]  # hts.고가
                low = rows[4]  # hts.저가
                close = rows[5]  # hts.종가
                volume = rows[6]  # hts.거래량

                cursor.execute('DELETE FROM ' + tableName + ' WHERE CODE=? and ymd=? and hms=?', (stock_code, ymd, hms,))
                cursor.execute('SELECT * FROM ' + tableName + ' WHERE CODE=? and ymd=? and hms=?', (stock_code, ymd, hms,))
                result = cursor.fetchone()
                if result == None:
                    cursor.execute("INSERT INTO " + tableName + "(CODE, NAME, ymd, hms, close, open, high, low, volume) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)",
                        (stock_code, stock_name, ymd, hms, close, open_v, high, low, volume))
            infp.close()
            print("insert...", stock_code, stock_name, fileName)

        conn.commit()
        cursor.close()
        conn.close()

        return

if __name__ == "__main__":
    PROJECT_HOME = os.path.join(os.path.dirname(os.path.join(os.path.dirname(os.path.join(os.path.dirname(__file__))))))
    RESOURCE_PATH = os.path.join(PROJECT_HOME, "resources")

    dbManager = DBManager()

    db_filename = os.path.join(RESOURCE_PATH, "hts.db")
    hts_dir = os.path.join(RESOURCE_PATH, "hts", "*.csv")
    dbManager.insert(db_filename, hts_dir)