# coding=utf-8 
import ujson
from binance.websocket.spot.websocket_client import SpotWebsocketClient as WebsocketClient
import time
import requests
#from loguru import logger
import datetime
import pymysql
import math


class NochainDbIf:
    def __init__(self, host="172.17.0.1", port=4423, user="root", password="2GS@bPYcgiMyL14A", dbname="ethdb"):
        self.conn = pymysql.connect(host=host, port=port, user=user, password=password, database=dbname,
                                    cursorclass=pymysql.cursors.DictCursor)
        print("init  nochain db suceess!")

    def save(self, day, price, ma350x2, ma111, ma350x1, ma350x1r6, ma350x3, ma350x5):
        with self.conn.cursor() as cursor:
            sql_insert = "REPLACE INTO `nochainv3a` (`unixdt`, `price`, `ma350x2`, `ma111`, ma350x1, ma350x1r6, ma350x3, ma350x5) VALUES (FROM_UNIXTIME(%s), %s, %s, %s, %s, %s, %s, %s)"
            # print(sql_insert)
            cursor.execute(sql_insert, (day, price, ma350x2, ma111, ma350x1, ma350x1r6, ma350x3, ma350x5))
        self.conn.commit()

def prepare_maxxx(prices, day, madays):
    total = 0
    cnt = 0
    for i in range(madays):
        if day in prices:
            total += prices[day]
            cnt += 1
            # print(day, total, cnt)
        day = str(int(day) - 3600 * 24)

    if cnt > 0:
        return total / cnt
    return 0

def prepare_ma350(prices, day):
    return prepare_maxxx(prices, day, 350)

def prepare_ma111(prices, day):
    return prepare_maxxx(prices, day, 111)

def prepare_gold_ratio(prices):
    ma350x1 = {}
    ma350x1r6 = {}
    ma350x2 = {}
    ma350x3 = {}
    ma350x5 = {}
    for day in prices:
        ma350x1[day] = prepare_maxxx(prices, day, 350)
        ma350x1r6[day] = ma350x1[day] * 1.6
        ma350x2[day] = ma350x1[day] * 2
        ma350x3[day] = ma350x1[day] * 3
        ma350x5[day] = ma350x1[day] * 5

    return ma350x1, ma350x1r6, ma350x2, ma350x3, ma350x5

def calc_pi_cycle_top(dbif, prices):
    ma350x2 = {}
    ma111 = {}
    for day in prices:
        ma350x2[day] = prepare_ma350(prices, day) * 2
        ma111[day] = prepare_ma111(prices, day)
    return ma350x2, ma111

def get_current_utc():
        curtime = time.gmtime(time.time())
        daystr = time.strftime("%d %b %Y", curtime)
        dayutc = int(time.mktime(time.strptime(daystr, "%d %b %Y")))
        return dayutc

def get_current_price():
    url = "https://data.messari.io/api/v1/assets/eth/metrics/market-data&interval=1d"
    header_set = {}
    header_set["x-messari-api-key"] = "aH2pyj5i4QGo1k1gLxXEbIJ5RJr+FYKLEWk6cRT6RuSc6lRY"
    response_price = requests.get(url, headers=header_set)
    if response_price.status_code == 200:
        priceweb = ujson.loads(response_price.content)
        if "data" in priceweb:
            priceset = priceweb["data"]
            if "market_data" in priceset:
                pricedata = priceset["market_data"]
                if "price_usd" in pricedata:
                    price = pricedata["price_usd"]
                    return price
    return None


def get_history_price(coin_id):
    prices = {}

    dayutc = get_current_utc()
    price = get_current_price()
    if price is not None:
        prices[str(dayutc)] = price
    print("start...", dayutc, price)

    dayt = time.gmtime()
    daystr = time.strftime("%Y", dayt)
    year = int(daystr)
    end_year = year
    while True:
        # if end_year < 2022:
        # break
        url = ""
        if end_year != year:
            start_year = end_year
            url = "https://data.messari.io/api/v1/assets/" + coin_id + "/metrics/price/time-series?start="
        else:
            url = "https://data.messari.io/api/v1/assets/" + coin_id + "/metrics/price/time-series?after=" + str(
                year) + "-01-01&order=descending&interval=1d"
        # now_time = time.gmtime()
        # daystr = time.strftime("%Y-%m-%d", now_time)
        # url = url + daystr + "&order=desc&format=json"
        if end_year != year:
            url = url + str(start_year) + "-01-01&end=" + str(end_year) + "-12-31&interval=1d&order=descending&interval=1d"
        header_set = {}
        header_set["x-messari-api-key"] = "aH2pyj5i4QGo1k1gLxXEbIJ5RJr+FYKLEWk6cRT6RuSc6lRY"
        # header_set["Content-Type"] = "application/json"
        print(header_set, url)
        response_supply = requests.get(url, headers=header_set)
        # print(response_supply)
        if response_supply.status_code == 200:
            #print(response_supply.content)
            supplyweb = ujson.loads(response_supply.content)
            if "data" in supplyweb:
                supplyset = supplyweb["data"]
                if "values" in supplyset:
                    valueset = supplyset["values"]
                    if valueset is not None:
                        for supply in valueset:
                            dayutc = int(supply[0] / 1000)
                            s = supply[1]
                            prices[str(dayutc)] = float(s)
                            # print(s, dayutc, supplys[str(dayutc)])
                            # break
                    else:
                        break
        else:
            break
        end_year -= 1
        time.sleep(2)
    return prices

def get_eth_history_price():
    return get_history_price("ethereum")

def nochain():
    global dbif
    dbif = NochainDbIf()
    print("prepare...")
    prices = get_eth_history_price()
    #print(prices)

    ma350x2, ma111 = calc_pi_cycle_top(dbif, prices)
    print("calc_pi_cycle_top ok.")
    ma350x1, ma350x1r6, ma350x2, ma350x3, ma350x5 = prepare_gold_ratio(prices);
    print("prepare_gold_ratio ok.")
    for day in prices:
        #print(day)
        ma350x21 = 0
        if day in ma350x2:
            ma350x21 = ma350x2[day]
        ma1111 = 0
        if day in ma111:
            ma1111 = ma111[day]

        ma350x11 = 0
        if day in ma350x1:
            ma350x11 = ma350x1[day]

        ma350x1r61 = 0
        if day in ma350x1r6:
            ma350x1r61 = ma350x1r6[day]

        ma350x31 = 0
        if day in ma350x3:
            ma350x31 = ma350x3[day]

        ma350x51 = 0
        if day in ma350x5:
            ma350x51 = ma350x5[day]

        # print(day, prices[day], ma350x21, ma1111, supply, issue, s2f_ratio1, s2f_deflection1)
        dbif.save(int(day), prices[day], ma350x21, ma1111, ma350x11,
                  ma350x1r61, ma350x31, ma350x51)
        #print("save ok.")

nochain()
