
# 获取 dalao所有关于此token的transfer记录 获取dalao的相关关系 例如 A buy token B sell token A transfer B 认为 A。B有关系 对于transfer 多个地址 路径长的 暂不考虑
from base_class import *
from base_class import BaseVariableFunction
import urllib.parse
import shutil
import random
import json
baseclass = BaseVariableFunction(__file__)

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---------------")


 
 
str_token_address=baseclass.str_token_address

df = pd.read_excel(baseclass.dalao_merge_path /
                  f"buytoken_df_{str_token_address}.xlsx",  dtype=object)

arr_str_dalaoaddress = []
arr_str_dalaoaddress=df["Maker"].drop_duplicates().tolist()

# arr_str_dalaoaddress=arr_str_dalaoaddress[0:100]
print(f"arr_str_dalaoaddress_len= {len(arr_str_dalaoaddress)}")



df =pd.DataFrame(
                columns=["timestamp", "sign", "source", 
                        "destination", "token", "amount"
                        ])
for str_dalao_address in arr_str_dalaoaddress:

    dalao_tokentransfer_solanafm_file = baseclass.dalao_tokentransfer_solanafm_path / str_token_address /f"{str_dalao_address}.json"
    new_dalao_tokentransfer_solanafm_file = baseclass.dalao_tokentransfer_solanafm_path / str_token_address /f"new_{str_dalao_address}.json"
    if not dalao_tokentransfer_solanafm_file.exists():
        continue
    
    new_arr_obj_dalao_transaction = []
    arr_obj_dalao_transaction =[]
    with dalao_tokentransfer_solanafm_file.open(mode='r') as f:
        arr_obj_dalao_transaction = json.load(f)

    for obj_dalao_transaction in arr_obj_dalao_transaction:
    
        sign = obj_dalao_transaction["transactionHash"]
        arr_obj_instruction_data = obj_dalao_transaction["data"]
        if len(arr_obj_instruction_data)!=1:
            continue
        obj_instruction_data = arr_obj_instruction_data[0]
        # for obj_instruction_data in arr_obj_instruction_data:
        if (obj_instruction_data["status"] != "Successful"):
            continue

        if obj_instruction_data["source"] in baseclass.arr_pub_address or obj_instruction_data["destination"] in baseclass.arr_pub_address :
            continue

        if (obj_instruction_data["action"] in ["transfer", "transferChecked","unknownTransfer"]):
            obj_instruction_data["sign"] = sign
            new_arr_obj_dalao_transaction.append(obj_instruction_data)

    if len(new_arr_obj_dalao_transaction)!=0 :
        with new_dalao_tokentransfer_solanafm_file.open(mode='w') as f:
            json.dump(new_arr_obj_dalao_transaction,f)
    cur_df = pd.DataFrame(new_arr_obj_dalao_transaction)
    if (len(cur_df) == 0):
        cur_df = pd.DataFrame(
            columns=["timestamp", "sign", "source", 
                    "destination", "token", "amount"
                    ])
        
    cur_df = cur_df[["timestamp", "sign",  "source",
            "destination", "token", "amount",
            ]]
    df = pd.concat([df,cur_df])
df.to_excel(baseclass.dalao_merge_path /f"relationship_{str_token_address}.xlsx",index=False )


total_dalao_txn_df = pd.read_excel(baseclass.dalao_merge_path /
                f"total_dalao_txn_{str_token_address}.xlsx", dtype=object)
relationship_df = pd.read_excel(baseclass.dalao_merge_path /
                f"relationship_{str_token_address}.xlsx", dtype=object)
relationship_df=relationship_df[["source",	"destination","token"]].drop_duplicates().reset_index(drop=True)
arr_dalao_relationship =[]
for index, row in relationship_df.iterrows():
    arr_cur_dalao = row.tolist()
    cur_source = row["source"]
    cur_destination = row["destination"]
    isin_set_dalao = False
    for set_dalao in arr_dalao_relationship:
        if (cur_source in set_dalao) or (cur_destination in set_dalao):
            set_dalao.add(cur_source)
            set_dalao.add(cur_destination)
            isin_set_dalao = True
            break
    if not isin_set_dalao:
        arr_dalao_relationship.append(set([ cur_source,cur_destination]))
    

arr_dalao_relationship = [list(set_dalao) for set_dalao in arr_dalao_relationship ] 
print(arr_dalao_relationship)

new_relationship_df = pd.DataFrame(arr_dalao_relationship)

new_relationship_df.to_excel( baseclass.dalao_merge_path/  f"new_relationship_{str_token_address}.xlsx",index=False )

total_dalao_txn_df["Maker_isrelation"] = 0
for arr_dalao in arr_dalao_relationship:
    total_dalao_txn_df.loc[total_dalao_txn_df["MAKER"].isin(arr_dalao), "MAKER"]= arr_dalao[0]
    total_dalao_txn_df.loc[total_dalao_txn_df["MAKER"].isin(arr_dalao), "Maker_isrelation"]= 1

total_dalao_txn_df.to_excel(baseclass.dalao_merge_path /
                f"rep_relationship_total_dalao_txn_{str_token_address}.xlsx", index=False)

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