

import random

from base_class import BaseVariableFunction
from base_class import *
baseclass = BaseVariableFunction(__file__)


baseclass.makedirpath(baseclass.dalao_tran_txhash_path)
old_print = print


def timestamped_print(*args, **kwargs):
    old_print(datetime.datetime.utcnow().replace(
        microsecond=0), *args, **kwargs)


print = timestamped_print
print('\n'*5)
print(f"{'{:<6}'.format('ENTER')} {baseclass.scriptfilename} ----------------NOTE-----------NOTE---------------")
# Python中windows路径的3种写法
# 可以是以下这样写：
utc_timeto = int(time.time())
utc_timefrom = int(utc_timeto - 17*24*3600)


df = pd.read_excel(baseclass.dalao_total_ana_fm_path /
                 "anaing_dalao.xlsx", dtype=object)

arr_str_dalaoAddress = df['add'].tolist()
arr_str_dalaoAddress.append(baseclass.mywalletaddress)
print('arr_str_dalaoAddress', len(arr_str_dalaoAddress))

for str_dalaoaddress in arr_str_dalaoAddress:
    print("str_dalaoaddress=", str_dalaoaddress)
    if not (baseclass.dalao_ori_tran_txhash_solscan_path/f"ori_txhash_{str_dalaoaddress}.csv").exists():
        continue
    obj_txhash_timestamp = {
        "txhash": [],
        "timestamp": [],
        "TokenAccount":[],
    }
    with open(baseclass.dalao_ori_tran_txhash_solscan_path /
              f"ori_txhash_{str_dalaoaddress}.csv", mode="r", encoding="utf-8") as f:
        arr_line = f.read().strip().split("\n")
        arr_line.pop(0)
        arr_line.pop()
        
        line =None
        try:
            for line in arr_line:
                if line.strip() == '':
                    continue 
                arr_split_line = line.split(",")
                if  " " in  arr_split_line[0] :
                    arr_split_line[0]= arr_split_line[0].strip()[1:]
                str_TokenAccount = arr_split_line[4].strip()
                if str_TokenAccount== str_dalaoaddress:
                    continue
                
                obj_txhash_timestamp["txhash"].append(arr_split_line[0])
                obj_txhash_timestamp["timestamp"].append(arr_split_line[1])
                obj_txhash_timestamp["TokenAccount"].append( str_TokenAccount)
        except Exception as e:
            print("error line=",line)
            raise
    new_df = pd.DataFrame(obj_txhash_timestamp)

    df = None
    if (baseclass.dalao_tran_txhash_path/f"txhash_{str_dalaoaddress}.csv").exists():
        df = pd.read_csv(baseclass.dalao_tran_txhash_path /
                         f"txhash_{str_dalaoaddress}.csv", dtype=object)
    df = pd.concat([new_df, df])
    df =df.replace('',np.nan)
    df =df.dropna(axis=0,how='any')
    df["timestamp"] = df["timestamp"].astype(int)
    df = df[df["timestamp"] >= utc_timefrom]

    df = df.drop_duplicates(subset=["txhash"]).reset_index(drop=True)
    df = df.sort_values(by=["timestamp"], ascending=[False])
    df.to_csv(baseclass.dalao_tran_txhash_path /
              f"txhash_{str_dalaoaddress}.csv", index=False)


print(f"{'{:<6}'.format('END')} {baseclass.scriptfilename} ----------------NOTE-----------NOTE---------------")
 