
# from datetime import datetime, timezone
# from playwright.async_api import async_playwright, Playwright
# from playwright.sync_api import expect
from playwright.async_api import Playwright, async_playwright, expect
import random

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

baseclass.makedirpath(baseclass.browsercookie_path)
baseclass.makedirpath(baseclass.dalao_ori_tran_txhash_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---------------")
# Python中windows路径的3种写法
# 可以是以下这样写：
utc_timeto = int(time.time())
utc_timefrom = int(utc_timeto - 17*24*3600)
utc_timeto = int(utc_timeto + 2*24*3600)

def get_dalao_historysign_solscan(df):

    utc_timeto = int(time.time())
    utc_timefrom = int(utc_timeto - 17*24*3600)
    utc_timeto = int(utc_timeto + 2*24*3600)
    # 示例   https://api.solscan.io/v2/account/txs/export?address=2D4dLL47vA1k1EN4421aM9DzKp3VBDAqKj8iUTSBLktw&type=tokenchange&timefrom=1711900800&timeto=1714492799.999&account_type=account_main
        # https://api-v2.solscan.io/v2/account/transfer/export?address=5bTgWQQE5Tb34BQQtUArj62PmFcVsaht2SGotAdq5fbt&activity_type[]=ACTIVITY_SPL_TRANSFER
    # https://api-v2.solscan.io/v2/account/balance_change/export?address=Cft4hKtC3dVftfqmL2MCALpeCq7oWM7qpftNfVVUzA7h&time_from=1719763200&time_to=1721051816.123&account_type=account_main
    
    df['SolscanTransferUrl'] = df.apply(lambda ser: (
        f"https://api-v2.solscan.io/v2/account/balance_change/export?address={ser['dalaoAddress']}&time_from={utc_timefrom}&time_to={utc_timeto}&account_type=account_main"), axis=1)

    
    return df


async def do_some_thing(playwright, cur_arr_str_dalaoAddress, cur_arr_str_dalaoSwapUrl):

    # browser =  playwright.chromium.launch(headless=True)
    context = await playwright.chromium.launch_persistent_context(user_data_dir=USER_DIR_PATH, accept_downloads=True, headless=True)
    # context = browser.new_context()
    context.set_default_timeout(9000)
    # context = await browser.new_context()
    arr_page = [None]*2
    arr_page[0] = await context .new_page()
    await arr_page[0].goto(
        "https://solscan.io/")

    print(context .pages)

    for str_dalaoAddress_idx in range(0, len(cur_arr_str_dalaoAddress)):

        str_dalaoAddress = arr_str_dalaoAddress[str_dalaoAddress_idx]
        str_dalaoTransferUrl = arr_str_dalaoSwapUrl[str_dalaoAddress_idx]
        print(f"enter str_dalaoAddress= {str_dalaoAddress}")
        print(f"enter str_dalaoTransferUrl= {str_dalaoTransferUrl}")
        print(f"cur_arr_str_dalaoAddress remainder = {len(cur_arr_str_dalaoAddress)-str_dalaoAddress_idx}")
        arr_page[1] = await context.new_page()
        page = arr_page[1]

        async with page.expect_download() as download_info:
            try:
                await page.goto(str_dalaoTransferUrl, timeout=0)
            except:
                # Wait for the download to start
                download = await download_info.value
                # Wait for the download process to complete
                print(await download.path())
                # Save downloaded file somewhere
                await download.save_as(baseclass.dalao_ori_tran_txhash_solscan_path / f"ori_txhash_{str_dalaoAddress}.csv")
            await page.wait_for_timeout(200)
        time.sleep(0.5)
        await page.close()

    await context.close()


async def get_onedriver_swapactivities(cur_arr_str_dalaoAddress, cur_arr_str_dalaoSwapUrl):
    async with async_playwright() as playwright:
        # playwright = Playwright().start()

        await do_some_thing(playwright, cur_arr_str_dalaoAddress,
                            cur_arr_str_dalaoSwapUrl)


async def main():
    print("enter main()")

    await get_onedriver_swapactivities(
        cur_arr_str_dalaoAddress=arr_str_dalaoAddress, cur_arr_str_dalaoSwapUrl=arr_str_dalaoSwapUrl)


utc_timeto = int(time.time())
utc_timefrom = int(utc_timeto - 17*24*3600)
utc_timeto = int(utc_timeto + 2*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)

arr_str_dalaoSwapUrl = [ f"https://api-v2.solscan.io/v2/account/balance_change/export?address={str_address}"
                        for str_address in arr_str_dalaoAddress]

print('arr_str_dalaoAddress', len(arr_str_dalaoAddress))
if len(arr_str_dalaoAddress)==0:
    raise("dalao txhash has get recently ,dont need get")
downloads_path = baseclass.dalao_ori_tran_txhash_solscan_path
USER_DIR_PATH = baseclass.browsercookie_path
asyncio.run(main())
print(f"{'{:<6}'.format('END')} {baseclass.scriptfilename} ----------------NOTE-----------NOTE---------------")
