import time
import os
import requests
import json
import hashlib
import logging
from osTools import *
# 设置日志格式
logging.basicConfig(format='%(asctime)s %(message)s', level=logging.INFO)

DIR = os.path.dirname(os.path.abspath(__file__))
IS_DEV = os.path.isfile(os.path.join(DIR, '.debug'))
# 定义base url
BASE_URL = "http://www.410eth.com:8088"

if IS_DEV:
    BASE_URL = "http://localhost:8088/ethmev"

class Auth:
    @staticmethod
    def build_auth(json_data):
        timestamp = int(time.time())
        ready_str = '410410' + str(timestamp)
        replaced_str = ready_str.replace(ready_str[-1:], '')

        json_data['timestamp'] = timestamp
        json_data['replace_str'] = replaced_str
        json_data['auth'] = hashlib.md5(replaced_str.encode('utf-8')).hexdigest()

        return json_data

class EthMevModel:
    @staticmethod
    def append_or_update(block_number, hash_code, data):
        url = BASE_URL + '/ethmev/appendOrUpdate'
        json_data = {
            'block': block_number,
            'hash': hash_code,
            'data': json.dumps(data),
        }
        json_data = Auth.build_auth(json_data)
        response = requests.post(url, data=json_data)
        return response.json()

    @staticmethod
    def find_by_block(block_number):
        url = BASE_URL + '/ethmev/findByBlock'
        json_data = {
            'block': str(block_number)
        }
        json_data = Auth.build_auth(json_data)
        response = requests.post(url, data=json_data).json()
        return response

    @staticmethod
    def find_by_hash(hash_code):
        url = BASE_URL + '/ethmev/findByHash'
        json_data = {
            'hash': hash_code
        }
        json_data = Auth.build_auth(json_data)
        response = requests.post(url, data=json_data)
        return response.json()

    @staticmethod
    def find_by_data_vague(data_vague):
        url = BASE_URL + '/ethmev/findByDataVague'
        json_data = {
            'dataVague': data_vague
        }
        json_data = Auth.build_auth(json_data)
        response = requests.post(url, data=json_data)
        return response.json()

    @staticmethod
    def find_by_block_or_hash_or_data_vague(block_number, hash_code, data_vague):
        url = BASE_URL + '/ethmev/findByHashOrBlockOrDataVague'
        json_data = {
            'block': block_number,
            'hash': hash_code,
            'dataVague': data_vague
        }
        json_data = Auth.build_auth(json_data)
        response = requests.post(url, data=json_data)
        return response.json()

    @staticmethod
    def find_sum2(token0, token1, level):
        url = BASE_URL + '/swappath/findBySumValueAndLevel'
        sumValue = hex(int(token0, 16) + int(token1, 16))
        json_data = {
            'sum_value': sumValue,
            'level': level
        }
        json_data = Auth.build_auth(json_data)
        response = requests.post(url, data=json_data)
        return response.json()

    @staticmethod
    def find_lp_route(lp):
        url = BASE_URL + '/swappath/findLevel2PathByLpAddress'

        json_data = {
            'lp_address': lp,
        }
        json_data = Auth.build_auth(json_data)
        response = requests.post(url, data=json_data)
        return response.json()
        #[{'factory': '0xC0AEe478e3658e2610c5F7A4A2E1777cE9e4f2Ac', 'LP': '0x397FF1542f962076d0BFE58eA045FfA2d347ACa0',
        # 'isEthW': False, 'feei': '3000', 'symbol1': 'WETH', 'symbol0': 'DEAD',
        # 'sum2': '0x160e313cb784589c3cbdff999568989d6727c580a', 'router': '0xd9e1ce17f2641f24ae83637ab66a2cca9c378b9f',
        # 'token0': '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', 'name': 'SUSHI_DEAD_WETH',
        # 'token1': '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2', 'decimals1': '18', 'id': 17,
        # 'decimals0': '6', 'r0': '454361158501473', 'r1': '324837295322546263677'},
        # {'factory': '0x9DEB29c9a4c7A88a3C0257393b7f3335338D9A9D', 'LP': '0x3Aa370AacF4CB08C7E1E7AA8E8FF9418D73C7e0F',
        # 'isEthW': False, 'feei': '3000', 'symbol1': 'WETH', 'symbol0': 'DEAD',
        # 'sum2': '0x160e313cb784589c3cbdff999568989d6727c580a', 'router': '0xCeB90E4C17d626BE0fACd78b79c9c87d7ca181b3',
        # 'token0': '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', 'name': 'CRO_DEAD_WETH',
        # 'token1': '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2', 'decimals1': '18', 'id': 1,
        # 'decimals0': '6', 'r0': '78658280524836', 'r1': '56258963016259372187'}]

    @staticmethod
    def delete_by_hash(hash_code):
        url = BASE_URL + '/ethmev/deleteByHash'
        json_data = {
            'hash': hash_code,
        }
        json_data = Auth.build_auth(json_data)
        response = requests.post(url, data=json_data)
        return json.loads(response.text)

def newBot(add):
    name = 'BOT.' + add[2:4]+ add[-2:]
    print(EthMevModel.append_or_update(2, add, {'name': name}))

def isHsInSql(hash):
    r = EthMevModel.find_by_hash(hash)
    if r['data']:
        return eval(r['data'][0]['data'])
    return False

def getSUM2Path(token0, token1):
    r = EthMevModel.find_sum2(token0, token1, 2)
    data = []
    if r['data']:
        r = eval(r['data']['data'])
    for lp2 in r:
        if lp2[0]['type'] != lp2[1]['type']:
            continue
        lp0 = lp2[0]['LP']
        lp1 = lp2[1]['LP']
        if {'lp0': lp0, 'lp1': lp1} in data:
            continue
        data.append({'lp0': lp0, 'lp1': lp1})
    return data

printTime('SQL:OK')

if __name__ == '__main__':
    #print('SQL:OK')
    #newBot('0x04156f068e0e8b5abe30fac002ae3b05529a3ddc')
    #printTime()
    #printTime((EthMevModel.find_by_block('topLp')['data']) + (EthMevModel.find_by_block('normalLp')['data']))
    printTime(speedTest(EthMevModel.find_by_hash, '0x123'))
    #printTime(EthMevModel.find_lp_route('0x397FF1542f962076d0BFE58eA045FfA2d347ACa0'))
    #printTime()
    #print(EthMevModel.append_or_update(1, '0xethw', {'name': 'ETHW', 'symbol': 'ETHW', 'decimals': 18}))
    #print(EthMevModel.append_or_update(2, '0xb4971d0dda22359ad86867362b7fc3206ea0d86b', {'name': '410.v4.0'}))
    #0x3b3ae79`0df4f312e745d270119c6052904fb6790
    #print(EthMevModel.find_by_hash('0xc5831a345bbc3fef632705ca72b5a16c5d0f2e22642a03cc22779cca56b2a0c8'))
    #print(EthMevModel.find_by_data_vague("0x19aec29cf3f52e3b0ac2ebe55c13070c979f88b89"))
    #print(EthMevModel.find_by_block_or_hash_or_data_vague(1, '', ''))
    #print(EthMevModel.delete_by_hash(123))
    #printTime((EthMevModel.find_by_block(15766460)))
    #dexArray = (EthMevModel.find_by_block(2))
    #tokenArray = (EthMevModel.find_by_block(1))
    #lpArray = (EthMevModel.find_by_block(0))

