 
import pandas as pd
import numpy as np
import random
import pandas as pd
from base_class import BaseVariableFunction
from base_class import *
baseclass = BaseVariableFunction(__file__)
baseclass.makedirpath(baseclass.dalao_config_st_solscan_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---------------")
activities_columns = ['txhash', 'date', 'timestamp', 'action', 'from', 'in_tokenaddress',
                      'out_tokenaddress',
                      'in_tokenname',
                      'out_tokenname',
                      'in_tokenamount',
                      'out_tokenamount',
                      'router',
                      'israydium',
                      ]


def setswaptokenname(gdf, str_dalaoAddress):
    arr_in_tokenname = gdf["in_tokenname"].tolist()
    arr_out_tokenname = gdf["out_tokenname"].tolist()
    arr_in_tokenaddress = gdf["in_tokenaddress"].tolist()
    arr_out_tokenaddress = gdf["out_tokenaddress"].tolist()

    str_swap_tokenname = arr_in_tokenname[0] if arr_in_tokenaddress[
        0] != "So11111111111111111111111111111111111111112" else arr_out_tokenname[0]
    gdf["swap_tokenname"] = str_swap_tokenname

    return gdf


def setswaptoken(gdf, str_dalaoAddress):
    arr_in_tokenaddress = gdf["in_tokenaddress"].tolist()
    arr_out_tokenaddress = gdf["out_tokenaddress"].tolist()

    str_swap_tokenaddress = arr_in_tokenaddress[0] if arr_in_tokenaddress[
        0] != "So11111111111111111111111111111111111111112" else arr_out_tokenaddress[0]
    gdf["swap_tokenaddress"] = str_swap_tokenaddress

    return gdf


def compute_eth_token_amount_onerow(row, str_dalaoAddress):
    row = row.copy()

    decimal_in_tokenamount = decimal.Decimal(
        row['in_tokenamount'])
    decimal_out_tokenamount = decimal.Decimal(
        row['out_tokenamount'])
    if row['in_tokenaddress'] == 'So11111111111111111111111111111111111111112':
        row['swap_eth_amount'] = '{0:.4f}'.format(
            decimal_in_tokenamount)
        row['swap_token_amount'] = '{0:.4f}'.format(
            - decimal_out_tokenamount)
        row['action'] = "SELL"

    elif row['in_tokenaddress'] != 'So11111111111111111111111111111111111111112':
        row['swap_eth_amount'] = '{0:.4f}'.format(
            -decimal_out_tokenamount)
        row['swap_token_amount'] = '{0:.4f}'.format(
            decimal_in_tokenamount)
        row['action'] = "BUY"

    return row


def compute_eth_token_amount(df, str_dalaoAddress):

    df = df.apply(lambda row: compute_eth_token_amount_onerow(
        row, str_dalaoAddress), axis=1)

    return df


def main():

    for str_dalao_idx in range(0, len(arr_str_dalaoAddress)):

        str_dalaoAddress = arr_str_dalaoAddress[str_dalao_idx]

        print(f"enter str_dalaoaddress= {str_dalaoAddress}")
        if not (baseclass.dalao_activities_solscan_path /
                f"solscan_act_{str_dalaoAddress}.csv").exists():
            continue
        df = pd.read_csv(baseclass.dalao_activities_solscan_path /
                         f"solscan_act_{str_dalaoAddress}.csv", dtype=object)
        if (len(df) == 0):
            continue

        mask_iswsol = (((df["in_tokenaddress"] == "So11111111111111111111111111111111111111112")
                        & (df["out_tokenaddress"] != "So11111111111111111111111111111111111111112"))

                       | (df["in_tokenaddress"] != "So11111111111111111111111111111111111111112")
                       & (df["out_tokenaddress"] == "So11111111111111111111111111111111111111112"))

        df = df[mask_iswsol].reset_index(drop=True)

        if len(df) == 0:
            continue
        df["swap_tokenaddress"] = ""

        df = df.groupby(by=["txhash"], group_keys=False).apply(
            lambda gdf: setswaptoken(gdf, str_dalaoAddress))
        df["swap_tokenname"] = ""
        df = df.groupby(by=["txhash"], group_keys=False).apply(
            lambda gdf: setswaptokenname(gdf, str_dalaoAddress))
        df["swap_eth_amount"] = "0"
        df["swap_token_amount"] = "0"
        df = compute_eth_token_amount(df=df, str_dalaoAddress=str_dalaoAddress)

        df["timestamp"] = df["timestamp"].astype(int)
        df["token_idx"] = -1

        gettokenidx_df = df[["timestamp", "swap_tokenaddress"]].copy()
        gettokenidx_df = gettokenidx_df.sort_values(
            by=["timestamp"], ascending=[True])
        list_tokenaddress = gettokenidx_df["swap_tokenaddress"].drop_duplicates(
        ).tolist()
        for str_tokenaddress_idx in range(0, len(list_tokenaddress)):
            str_tokenaddress = list_tokenaddress[str_tokenaddress_idx]
            df.loc[df["swap_tokenaddress"] == str_tokenaddress,
                   "token_idx"] = len(list_tokenaddress)-str_tokenaddress_idx

        df = df.sort_values(by=["token_idx", "timestamp"], ascending=[
            True, True]).reset_index(drop=True)
        df.to_csv(baseclass.dalao_config_st_solscan_path /
                  f"configtoken_{str_dalaoAddress}.csv", index=False)


df = pd.read_csv(baseclass.dalao_merge_path /
                 "filter_dalao.csv", dtype=object)

arr_str_dalaoAddress = df["dalaoAddress"].tolist()

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