import sqlite3

from config import *
from HTS2 import HTS
from monitor_coin import MonitorCoin

monitorCoin = MonitorCoin()
hts = HTS()


def inserData(symbol, interval, data):
    conn = sqlite3.connect('./resources/coins.db')
    cursor = conn.cursor()

    tableName = "{}_{}".format(symbol, str(interval))
    # 테이블/키 생성
    cursor.execute("CREATE TABLE IF NOT EXISTS {} (CODE text, NAME text, ymdhms datetime, ymd text, hms text, Close REAL, Open REAL, High REAL, Low REAL, Volume REAL)".format(tableName))
    cursor.execute("CREATE INDEX IF NOT EXISTS {}_idx on {}(CODE, ymdhms)".format(tableName, tableName))

    for i in range(len(data)):
        ymd = data.index[i].strftime('%Y%m%d')
        hms = data.index[i].strftime('%H%M%S')
        ymdhms = data.index[i].strftime('%Y-%m-%d %H:%M:%S')
        Open = data.Open.iloc[i]
        High = data.High.iloc[i]
        Low = data.Low.iloc[i]
        Close = data.Close.iloc[i]
        Volume = data.Volume.iloc[i]

        cursor.execute("SELECT * from {} where CODE = ? and ymdhms = ?".format(tableName), (symbol, ymdhms, ))
        arr = cursor.fetchone()
        if arr:
            cursor.execute("UPDATE {} SET Close=?, Open=?, High=?, Low=?, Volume=? where CODE=? and ymdhms=?".format(tableName), (Close, Open, High, Low, Volume, symbol, ymdhms))
        else:
            cursor.execute("INSERT INTO {} (CODE, NAME, ymdhms, ymd, hms, Close, Open, High, Low, Volume) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)".format(tableName), (symbol, KR_COINS[symbol], ymdhms, ymd, hms, Close, Open, High, Low, Volume))

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

def download():
    """
    KR_COINS = {
        "AVAX": "아발란체",
        "BTC": "비트코인",
        "ETC": "이더리움",
        "SOL": "솔라나",
    }
    """
    for symbol in KR_COINS:
        print(symbol)

        # 1주
        interval = 10080
        data = monitorCoin.get_coin_more_data(symbol, interval, bong_count=5000)
        if data is not None and not data.empty:
            try:
                inserData(symbol, interval, data)
            except Exception as e:
                print(f"Error processing data for {symbol}: {str(e)}")

        # 1달
        interval = 43200
        data = monitorCoin.get_coin_more_data(symbol, interval, bong_count=5000)
        if data is not None and not data.empty:
            try:
                inserData(symbol, interval, data)
            except Exception as e:
                print(f"Error processing data for {symbol}: {str(e)}")

        # 1일
        interval = 1440
        data = monitorCoin.get_coin_more_data(symbol, interval, bong_count=5000)
        if data is not None and not data.empty:
            try:
                inserData(symbol, interval, data)
            except Exception as e:
                print(f"Error processing data for {symbol}: {str(e)}")

        # 60분
        interval = 60
        data = monitorCoin.get_coin_more_data(symbol, interval, bong_count=10000)
        if data is not None and not data.empty:
            try:
                inserData(symbol, interval, data)
            except Exception as e:
                print(f"Error processing data for {symbol}: {str(e)}")

        # 30분
        interval = 30
        data = monitorCoin.get_coin_more_data(symbol, interval, bong_count=10000)
        if data is not None and not data.empty:
            try:
                inserData(symbol, interval, data)
            except Exception as e:
                print(f"Error processing data for {symbol}: {str(e)}")

        # 5분
        interval = 5
        data = monitorCoin.get_coin_more_data(symbol, interval, bong_count=10000)
        if data is not None and not data.empty:
            try:
                inserData(symbol, interval, data)
            except Exception as e:
                print(f"Error processing data for {symbol}: {str(e)}")

        # 1분
        interval = 1
        data = monitorCoin.get_coin_more_data(symbol, interval, bong_count=10000)
        if data is not None and not data.empty:
            try:
                inserData(symbol, interval, data)
            except Exception as e:
                print(f"Error processing data for {symbol}: {str(e)}")

    return

if __name__ == "__main__":
    download()
