// ==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_thead_arr() {

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



var pre_timestamp = -1;
var now_timestamp = -1;
async function get_tbody_data() {

    let div_has_tran_table = document.querySelector("div.chakra-tabs__tab-panels.css-2zi8qu");
    let tbody = div_has_tran_table.querySelector("tbody.g-table-tbody");

    let arr_tbody_trs;
    arr_tbody_trs = Array.from(tbody.children);
    arr_tbody_trs.shift();


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

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

        let tdtexts = [];
        // if (arr_tds.length != 10) {
        //     continue;
        // }
        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 = parseFloat(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) {
                // bought


                let str_sol = "0";
                let str_token_amount = "0";
                let float_sol;

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

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

                float_sol = parseFloat(str_sol);
                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];
                    }
                }
                tdtexts.push(float_sol);

            } else if (i == 3) {
                // sold
                let str_sol = "0";
                let str_token_amount = "0";
                let float_sol;

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

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

                float_sol = parseFloat(str_sol);
                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];
                    }
                }
                tdtexts.push(float_sol);




            } else if (i == 4) {
                // 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 == 5) {
                // Realized
                continue;
            }
            else if (i == 6) {
                // UnRealized
                continue

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

            } else if (i == 8) {
                // TXs

            } else if (i == 9) {
                // Last Active

            }

        }
        res_data.push(tdtexts);

    }


}

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

    funcDownload(res_data.join(""), urlpathname + "_top_gmgn_sol" + "_" + parseInt(Date.now() / 1000) + ".csv");
    res_data = [];

}
function autoScroll() {
    console.log("enter autoScroll");

    let interval;
    let scroll_times = 15;

    let div_has_tran_table = document.querySelector("div.chakra-tabs__tab-panels.css-2zi8qu");
    let tbody = div_has_tran_table.querySelector("div.css-1o2kb31 tbody.g-table-tbody");


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

            let tbodytrs;

            if (scroll_times > 0) {

                await sleep(150);
                tbodytrs = tbody.children;
                tbodytrs[tbodytrs.length - 1].scrollIntoView({ behavior: "smooth", block: "start" });


            } else {
                clearInterval(interval);
                await get_tbody_data();
                save_resdata();
                return;

            }
            scroll_times--;


            tbodytrs = tbody.children;
            if (tbodytrs.length == 101) {
                clearInterval(interval);
                await get_tbody_data();
                save_resdata();
                return;

            }

            await sleep(300);
        }, 1200)

    }

    down()

}



var res_data = [];
var sTop = 0;

// window.addEventListener('load', async () => {

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

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

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


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

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

    async function clickButton() {
        res_data = [];

        console.log("enter clickButton res_data=", res_data);
        let div_chakra_tabs = document.querySelector('[role="tablist"]');
        let arr_buttons_chakra = Array.from(div_chakra_tabs.querySelectorAll("button"));
        let button_top_trader = undefined;
        for (let button of arr_buttons_chakra) {
            if (button.innerText.includes("Top Traders")) {
                button_top_trader = button;
                break;
            }
        }
        if (button_top_trader == undefined) {
            console.log("no button_top_trader");
            return;
        }
        await button_top_trader.click();
        await sleep(7000);

        let div_has_tran_table;
        let _tbody;
        let _thead;

        // chakra-tabs__tablist css-1p75jc5
        div_has_tran_table = document.querySelector("div.chakra-tabs__tab-panels.css-2zi8qu");
        _tbody = div_has_tran_table.querySelector("div.css-1o2kb31 tbody.g-table-tbody");
        _thead = div_has_tran_table.querySelector("div.css-1o2kb31 thead.g-table-thead");
        let arr_th = _thead.querySelectorAll("th");
        let click_USD = arr_th[1].querySelector("div.css-1vimx2u");
        if (click_USD.innerText.includes("USD")) {
            await click_USD.click();
            await sleep(4000);
        }




        let titlearr = get_thead_arr();
        res_data.push(titlearr);
        autoScroll();

    }

})();




