
from base_class import BaseVariableFunction
from base_class import *
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---------------")
 

def makescreenurl( urlname,urlparam):
    _url = urlname + urlparam
    return '=HYPERLINK("{}","{}")'.format(_url, _url)

url = "https://solana-mainnet.g.alchemy.com/v2/pxF-cEkEE1JxzxgotGyww5ra5w1IvAkJ"


payload_getTokenAccountsByOwner = {
  
}
headers = {
    "accept": "application/json",
    "content-type": "application/json"
}

 
    

def init_payload():
    
    global payload_getTokenAccountsByOwner
    payload_getTokenAccountsByOwner = {
    "id": 1,
    "jsonrpc": "2.0",
    "method": "getTokenAccountsByOwner",
     "params": [ "",
                
                {
            "mint":str_tokenaddress
        }, {
            "encoding": "jsonParsed"
        }
                
                ],
}
    
    return




def get_dalao_ata():
    df_top_gmgn_sol = pd.DataFrame(columns=["Maker","ATA"])
    df_holder_gmgn_sol  = pd.DataFrame(columns=["Maker","ATA"])
    if (baseclass.analysis_token_path /str_tokenaddress/
                       f"{str_tokenaddress}_top_gmgn_sol.csv").exists():
        df_top_gmgn_sol = pd.read_csv(baseclass.analysis_token_path /str_tokenaddress/
                       f"{str_tokenaddress}_top_gmgn_sol.csv", dtype=object)
        if "ATA" not in df_top_gmgn_sol.columns:
            df_top_gmgn_sol["ATA"] = "0"
            
        
    if (baseclass.analysis_token_path /str_tokenaddress/
                       f"{str_tokenaddress}_holder_gmgn_sol.csv").exists():
        df_holder_gmgn_sol = pd.read_csv(baseclass.analysis_token_path /str_tokenaddress /
                       f"{str_tokenaddress}_holder_gmgn_sol.csv", dtype=object)
        if "ATA" not in df_holder_gmgn_sol.columns:
            df_holder_gmgn_sol["ATA"] = "0"
 
    df =  pd.concat([df_top_gmgn_sol[["Maker","ATA"]], df_holder_gmgn_sol[["Maker","ATA"]]], ignore_index=True)
  
 
    df=df[df["ATA"]=="0"].reset_index(drop=True)
    arr_dalaoaddress = df["Maker"].drop_duplicates().tolist()
 
 
    while len(arr_dalaoaddress)>0:
        if len(arr_dalaoaddress)%10==0:
            print(f"remainder len = {len(arr_dalaoaddress)}")
        
        str_dalaoaddress =arr_dalaoaddress[0]
        print(f"str_dalaoaddress= {str_dalaoaddress} ")
        payload_getTokenAccountsByOwner["params"][0] =str_dalaoaddress
        
        req_response = requests.post(url, json=payload_getTokenAccountsByOwner, headers=baseclass.headers,timeout=10)
        if req_response.status_code != 200:
            print(" req_response.status_code=", req_response.status_code)
            time.sleep(2)
            continue
        arr_dalaoaddress.pop(0)
        # if str_dalaoaddress !="4LQuLeQYrAsqHtsJ3s15dT8A4Jpbr6iEKnK2DJAL7ZNo":
        #     continue
        response_data = req_response.json() 
        # response_data = req_response.json()
        ata_addata_address = "-1"
        if len( response_data["result"]["value"])==0:
            ata_addata_address ="-1"
        else:
            ata_addata_address =  response_data["result"]["value"][0]["pubkey"]  
            
        df_top_gmgn_sol.loc[df_top_gmgn_sol["Maker"]==str_dalaoaddress,"ATA"] = ata_addata_address 
        df_holder_gmgn_sol.loc[df_holder_gmgn_sol["Maker"]==str_dalaoaddress,"ATA"] = ata_addata_address
        print(f"ata_addata_address= {ata_addata_address}")
   
        if len(arr_dalaoaddress)%5==0 or len(arr_dalaoaddress)<=2:
            if (baseclass.analysis_token_path /str_tokenaddress/
                            f"{str_tokenaddress}_top_gmgn_sol.xlsx").exists():
                df_top_gmgn_sol.to_excel(baseclass.analysis_token_path /str_tokenaddress/
                            f"{str_tokenaddress}_top_gmgn_sol.xlsx",index=False )
                df_top_gmgn_sol.to_csv(baseclass.analysis_token_path /str_tokenaddress/
                            f"{str_tokenaddress}_top_gmgn_sol.csv",index=False )
            if (baseclass.analysis_token_path /str_tokenaddress/
                            f"{str_tokenaddress}_holder_gmgn_sol.xlsx").exists():
                df_holder_gmgn_sol.to_excel(baseclass.analysis_token_path /str_tokenaddress/
                            f"{str_tokenaddress}_holder_gmgn_sol.xlsx", index=False )
    
                df_holder_gmgn_sol.to_csv(baseclass.analysis_token_path /str_tokenaddress/
                            f"{str_tokenaddress}_holder_gmgn_sol.csv", index=False )
    return



str_tokenaddress = "4GULMPKBJLruChBZWksZzukAg1AjSCmCTMn9ny2Xpump"
 
init_payload()
get_dalao_ata()

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

