// ==UserScript==
// @name         GMGN-Get-Top
// @namespace    http://tampermonkey.net/
// @version      2024-10-19
// @description  try to take over the world!
// @author       You
// @match        https://gmgn.ai/sol/token/*
// @icon         https://www.google.com/s2/favicons?sz=64&domain=gmgn.ai
// @grant        none
// ==/UserScript==


function funcDownload(content, filename) {
    console.log('begin download');
    // 创建隐藏的可下载链接
    let eleLink = document.createElement('a');
    eleLink.download = filename;
    eleLink.style.display = 'none';
    // 字符内容转变成blob地址
    let blob = new Blob([content]);
    eleLink.href = URL.createObjectURL(blob);
    // 触发点击
    document.body.appendChild(eleLink);
    eleLink.click();
    // 然后移除
    document.body.removeChild(eleLink);
}


function sleep(sleepdelay) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve(sleepdelay);
        }, sleepdelay);
    })
}

var number_chars_obj = {
    "k": 3,
    "m": 6,
    "b": 9,
    "t": 12,
    "p": 15
};

var number_chars_arr = ["k", "m", "b", "t", "p"];
function get_float_number(str_number) {
    let float_number = parseFloat(str_number);
    for (let number_char of number_chars_arr) {
        if (str_number.indexOf(number_char) != -1) {
            float_number = parseFloat(str_number) * 10 ** number_chars_obj[number_char];
        }
    }
    return float_number;
}

function getCurrentTime() {
    const zeroFill = (i) => {
        if (i >= 0 && i <= 9) {
            return "0" + i;
        } else {
            return '' + i;
        }

    }
    let date = new Date();//当前时间
    let year = date.getFullYear();
    let month = zeroFill(date.getMonth() + 1);//月
    let day = zeroFill(date.getDate());//日
    let hour = zeroFill(date.getHours());//时
    let minute = zeroFill(date.getMinutes());//分
    let second = zeroFill(date.getSeconds());//秒

    //当前时间
    var curTime = month + day + '_' + hour + minute;
    return curTime;
}


function get_thead_arr_toptrader() {

    // let titlearr = _thead.innerText.trim().split(/\r?\n/);
    let titlearr = ['Maker', 'SOL', 'Buy_sol', 'Buy_token_M', 'buy_cout', 'Sell_sol', 'Sell_token_M', 'sell_cout', 'Pnl_sol', 'Pnl_per',];
    return titlearr;
}

async function get_tbody_data_toptrader() {

    let div_has_tran_table = document.querySelector("div.ag-root-wrapper-body.ag-focus-managed.ag-layout-normal > div.ag-root.ag-unselectable.ag-layout-normal.ag-body-vertical-content-no-gap.ag-body-horizontal-content-no-gap");


    let tbody = div_has_tran_table.querySelector("div.ag-body.ag-layout-normal div.ag-center-cols-viewport div.ag-center-cols-container");

    let arr_tbody_trs;
    arr_tbody_trs = Array.from(tbody.children);
    let last_tr = arr_tbody_trs[arr_tbody_trs.length - 1];
    let last_row_id = parseInt(last_tr.getAttribute('row-index'));
    if (arr_res_data_toptrader.length - 1 >= last_row_id + 1) {
        // 这批已经全部获取了 
        return false;
    }


    for (let i = 0; i < arr_tbody_trs.length; i++) {

        let cur_row_id = parseInt(arr_tbody_trs[i].getAttribute('row-index'));
        if (arr_res_data_toptrader.length - 1 >= cur_row_id + 1) {
            continue;
        }

        let arr_tds;
        arr_tds = Array.from(arr_tbody_trs[i].children);

        let tdtexts = [];
        for (let i = 0; i < arr_tds.length; i++) {
            if (i == 0) {
                // trader
                let a_element = arr_tds[i].querySelector("a");
                let str_trader = a_element.href.split('/').pop();
                tdtexts.push(str_trader);

            }
            else if (i == 1) {
                //sol balance   

                let str_balance = arr_tds[i].innerText.trim().replace(/[,]/g, "").trim();
                str_balance = str_balance.replace(/\s+/g, "");

                str_balance = str_balance.toLowerCase();
                let float_balance;

                float_balance = get_float_number(str_balance);
                // for (let number_char of number_chars_arr) {
                //     if (str_balance.indexOf(number_char) != -1) {
                //         float_balance = parseFloat(str_balance) * 10 ** number_chars_obj[number_char];
                //     }
                // }
                tdtexts.push(float_balance);

            } else if (i == 2) {
                continue;
            }

            else if (i == 3) {
                // bought

                // sol
                // token txns

                let arr_sol_amount_txns = arr_tds[i].children[0].children;
                // if (arr_sol_amount_txns.length == 1) {
                //     // 为 --
                //     tdtexts.push(0);
                //     tdtexts.push(0);
                //     tdtexts.push(0);
                //     continue;
                // }


                let str_sol = "0";
                let float_sol;
                str_sol = arr_sol_amount_txns[0].innerText.trim().toLowerCase();
                str_sol = str_sol.replace(/[sol$,%\+><]/g, "").trim();
                // if (str_sol == "--") {
                //     str_sol = "0";
                // }

                let str_token_amount = "0";
                let float_token_amount;
                let arr_token_amount_txns = [];
                let float_txns;


                arr_token_amount_txns = arr_sol_amount_txns[1].innerText.trim().toLowerCase().split('/');
                str_token_amount = arr_token_amount_txns[0].trim();
                str_txns = arr_token_amount_txns[1].trim();

                float_sol = get_float_number(str_sol);
                tdtexts.push(float_sol);

                float_token_amount = get_float_number(str_token_amount);
                float_txns = get_float_number(str_txns);
                tdtexts.push(float_token_amount / 1e6);
                tdtexts.push(float_txns);

            } else if (i == 4) {
                // sold

                let arr_sol_amount_txns = arr_tds[i].children[0].children;
                // if (arr_sol_amount_txns.length == 1) {
                //     tdtexts.push(0);
                //     tdtexts.push(0);
                //     tdtexts.push(0);
                //     continue;
                // }

                let str_sol = "0";
                let float_sol;
                str_sol = arr_sol_amount_txns[0].innerText.trim().toLowerCase();
                str_sol = str_sol.replace(/[sol$,%\+><]/g, "").trim();
                // if (str_sol == "--") {
                //     str_sol = "0";
                // }
                let str_token_amount = "0";
                let float_token_amount;
                let arr_token_amount_txns = [];
                let float_txns;


                arr_token_amount_txns = arr_sol_amount_txns[1].innerText.trim().toLowerCase().split('/');
                str_token_amount = arr_token_amount_txns[0].trim();
                str_txns = arr_token_amount_txns[1].trim();

                float_sol = get_float_number(str_sol);
                tdtexts.push(float_sol);

                float_token_amount = get_float_number(str_token_amount);
                float_txns = get_float_number(str_txns);
                tdtexts.push(float_token_amount / 1e6);
                tdtexts.push(float_txns);


            } else if (i == 5) {
                // pnl

                let str_sol = "0";
                let str_percent = "0";
                let float_sol = 0;
                let float_percent = 0;

                let arr_sol_percent = arr_tds[i].children[0].children;


                str_sol = arr_sol_percent[0].innerText.trim().toLowerCase();
                str_sol = str_sol.replace(/[sol$,%\+><]/g, "").trim();
                str_percent = arr_sol_percent[1].innerText.trim().toLowerCase();
                str_percent = str_percent.replace(/[sol$,%\+><]/g, "").trim();

                if (str_sol == "--") {
                    str_sol = "0";
                }

                if (str_percent == "--") {
                    str_percent = "999999";
                }


                float_sol = parseFloat(str_sol);
                float_percent = parseFloat(str_percent);
                for (let number_char of number_chars_arr) {
                    if (str_sol.indexOf(number_char) != -1) {
                        float_sol = parseFloat(str_sol) * 10 ** number_chars_obj[number_char];
                    }
                    if (str_percent.indexOf(number_char) != -1) {
                        float_percent = parseFloat(str_percent) * 10 ** number_chars_obj[number_char];
                    }

                }
                tdtexts.push(float_sol);
                tdtexts.push(float_percent);

            } else if (i == 6) {
                // Realized
                continue;
            }
            else if (i == 7) {
                // UnRealized
                continue

            } else if (i == 8) {
                //Holding Duration
                continue

            }
            else if (i == 9) {
                // Avg Cost/Sold
                continue

            } else if (i == 10) {
                // Last Active
                continue

            }

        }
        arr_res_data_toptrader.push(tdtexts);

    }
    return true

}


function save_resdata_toptrader() {
    console.log("enter save_resdata_toptrader");
    arr_res_data_toptrader.forEach((val, index, arr) => { arr[index] = val.join() + "\n" });
    let urlpathname = window.location.pathname.slice(1).split('/');
    urlpathname = urlpathname.pop()

    funcDownload(arr_res_data_toptrader.join(""), urlpathname + "_top_gmgn_sol" + "_" + getCurrentTime() + ".csv");
    arr_res_data_toptrader = [];

}


function autoScroll_toptrader() {
    console.log("enter autoScroll_toptrader");

    let interval;
    let scroll_times = 15;


    let div_has_tran_table = document.querySelector("div.ag-root-wrapper-body.ag-focus-managed.ag-layout-normal > div.ag-root.ag-unselectable.ag-layout-normal.ag-body-vertical-content-no-gap.ag-body-horizontal-content-no-gap");
    let tbody = div_has_tran_table.querySelector("div.ag-body.ag-layout-normal div.ag-center-cols-viewport div.ag-center-cols-container");


    async function down() {
        interval = setInterval(async () => {

            let tbodytrs;
            console.log("scroll_times=", scroll_times);

            if (scroll_times > 0) {

                await sleep(150);
                tbodytrs = tbody.children;
                tbodytrs[tbodytrs.length - 1].scrollIntoView({ behavior: "smooth", block: "center" });
                let bool_get_tbody = await get_tbody_data_toptrader();
                if (bool_get_tbody == false) {
                    scroll_times = 0;
                }


            } else {
                clearInterval(interval);
                await get_tbody_data_toptrader();
                save_resdata_toptrader();
                return;

            }
            scroll_times--;


            // tbodytrs = tbody.children;
            if (arr_res_data_toptrader.length == 101) {
                clearInterval(interval);
                await get_tbody_data_toptrader();
                save_resdata_toptrader();
                return;

            }

            await sleep(300);
        }, 1200)

    }

    down()

}


var arr_res_data_toptrader = [];
// window.addEventListener('load', async () => {

(async function () {
    console.log("enter load");
    await sleep(6000);
    console.log("create button");

    var mydivbox = document.createElement("div");

    var button_get_toptrader = document.createElement("button");//创建 获取 top trader 一个按钮
    button_get_toptrader.className = "tam-mybutton-gettran"
    button_get_toptrader.textContent = "top_sol"; //按钮内容
    button_get_toptrader.style.width = "90px"; //按钮宽度
    button_get_toptrader.style.height = "20px"; //按钮高度
    button_get_toptrader.style.align = "center"; //文本居中
    button_get_toptrader.style.color = "blue"; //按钮文字颜色
    button_get_toptrader.style.background = "#717171"; //按钮底色
    button_get_toptrader.style.border = "1px solid #717171"; //边框属性

    mydivbox.appendChild(button_get_toptrader);

    mydivbox.style.position = "fixed";
    mydivbox.style.top = "160px";
    mydivbox.style.right = "40px";
    document.body.appendChild(mydivbox);



    button_get_toptrader.addEventListener("click", clickButton_get_toptrader); //监听按钮点击事件


})();

async function clickButton_get_toptrader() {
    arr_res_data_toptrader = [];

    console.log("enter clickButton_toptrader arr_res_data_toptrader=", arr_res_data_toptrader);
    let div_chakra_tabs = document.querySelector('[role="tablist"]');
    let arr_buttons_chakra = Array.from(div_chakra_tabs.querySelectorAll("button"));
    let tab_top_trader_click = undefined;
    for (let button of arr_buttons_chakra) {
        if (button.innerText.includes("Traders")) {
            tab_top_trader_click = button;
            break;
        }
    }
    if (tab_top_trader_click == undefined) {
        console.log("no tab_top_trader_click");
        return;
    }
    console.log("  tab_top_trader_click click=");
    await tab_top_trader_click.click();
    await sleep(7000);
    let div_has_tran_table = document.querySelector("div.ag-root-wrapper-body.ag-focus-managed.ag-layout-normal > div.ag-root.ag-unselectable.ag-layout-normal.ag-body-vertical-content-no-gap.ag-body-horizontal-content-no-gap");
    let _thead = div_has_tran_table.querySelector("div.ag-header.ag-pivot-off.ag-header-allow-overflow div.ag-header-viewport div.ag-header-row.ag-header-row-column ");


    let arr_th = _thead.children;
    let tab_click_USD_toptrader = arr_th[5].querySelector("div.css-1vimx2u");
    if (tab_click_USD_toptrader.innerText.includes("USD")) {
        await tab_click_USD_toptrader.click();
        await sleep(4000);
    }

    let titlearr = get_thead_arr_toptrader();
    arr_res_data_toptrader.push(titlearr);
    autoScroll_toptrader();

}


