// ==UserScript==
// @name         DexScreen-GetTopTrader
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       You
// @match        https://dexscreener.com/solana/*
// @icon         https://www.google.com/s2/favicons?sz=64&domain=tampermonkey.net
// @grant        none

// ==/UserScript==



function funcDownload(content, filename) {
    console.log('begin download');
    // 创建隐藏的可下载链接
    var eleLink = document.createElement('a');
    eleLink.download = filename;
    eleLink.style.display = 'none';
    // 字符内容转变成blob地址
    var 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"];

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

(async function () {
    console.log("enter load");

    var res = [];

    await sleep(6000);
    console.log("create button");

    var input = document.createElement("input") //创建一个input文本框
    input.value = "350";
    input.className = "tam-myinput"
    input.type = "number"


    var mydivbox = document.createElement("div");
    var button = document.createElement("button");//创建一个按钮
    var button_toptraders = document.createElement("button");//创建 获取toptraders一个按钮
    mydivbox.appendChild(input);
    mydivbox.appendChild(button);
    mydivbox.appendChild(button_toptraders);



    button_toptraders.className = "tam-mybutton-gettop";
    button_toptraders.textContent = "gettop"; //按钮内容
    button_toptraders.style.width = "90px"; //按钮宽度
    //button.style.height = "28px"; //按钮高度
    button_toptraders.style.align = "center"; //文本居中
    button_toptraders.style.color = "blue"; //按钮文字颜色
    button_toptraders.style.background = "#e33e33"; //按钮底色
    button_toptraders.style.border = "1px solid #e33e33"; //边框属性
    button_toptraders.addEventListener("click", clickBotton); //监听按钮点击事件


    mydivbox.style.position = "fixed";
    mydivbox.style.top = "60px";
    mydivbox.style.right = "60px";

    document.body.appendChild(mydivbox)


    // var parentdiv = document.getElementsByClassName("custom-1275zxc")[0];
    // parentdiv.insertBefore(mydivbox, parentdiv.getElementsByTagName("div")[0]);
    // parentdiv.appendChild(mydivbox);
    var theadtr = document.getElementsByClassName("custom-19qkkht")[0].getElementsByTagName("thead")[0];
    theadtr.style.color = "blue";

    function get_thead_arr(_thead) {
        let titlearr = _thead.innerText.trim().split(/\r?\n/);
        // titlearr = titlearr.slice(1, 5);

        titlearr = [
            "Rank",
            "Maker",
            "Buymoney",
            "Sellmoney",
            "Earn",
            "Earnper",
            "Buycount",
            "Sellcount",
            "Buyamount",
            "Sellamount",
            "Amountper",
            "TokenAddress",
            "isNormal",


        ]
        return titlearr;
    }
    function get_tbodyarr(tbody_arr) {
        let urlpathname_arr = window.location.pathname.slice(1).split('/');
        let token_address = urlpathname_arr[1];

        for (let idx = 0; idx < tbody_arr.length; idx++) {
            let tr = tbody_arr[idx];
            let tds_arr = Array.from(tr.children);
            let td_value_obj = {
                "Rank": "0",
                "Maker": "",
                "Buymoney": 0,
                "Sellmoney": 0,
                "Earn": 0,
                "Earnper": 0,
                "Buycount": 0,
                "Sellcount": 0,
                "Buyamount": 0,
                "Sellamount": 0,
                "Amountper": 0,
                "TokenAddress": token_address,
                "isNormal": -1,


            }
            let temp_innertext;
            for (let i = 0; i < tds_arr.length; i++) {
                if (i == 1 || i == 4 || i == 5 || i == 6 || i == 7) {
                    continue;
                } else if (i == 0) {
                    let td_innerText = tds_arr[i].innerText.trim().replace(/#/g, "");
                    td_value_obj.Rank = td_innerText;

                }
                else if (i == 8) {
                    td_value_obj.Maker = tds_arr[i].querySelector("a").href.split('/').pop();

                } else if (i == 2 || i == 3) {
                    // 获取 Bought
                    // '<$0.1\n10/1 txns'
                    // '-'
                    let td_innerText = tds_arr[i].innerText.trim().toLowerCase();
                    let money = 0, amount = 0, count = 0;

                    if (td_innerText == "-") {
                        if (i == 2) {
                            td_value_obj.Buycount = 0;
                            td_value_obj.Buymoney = 0;
                        } else {
                            td_value_obj.Sellcount = 0;
                            td_value_obj.Sellmoney = 0;
                        }
                        continue;
                    }
                    if (td_innerText.indexOf("$") == -1) {
                        console.log("idx=", idx, "td_innerText=", td_innerText);
                        throw ("td_innerText error");
                    }

                    td_innerText = td_innerText.replace(/[(\$),]/g, "");
                    let td_innerText_arr = td_innerText.split(/\r?\n/);
                    td_innerText_arr.forEach((val, index, arr) => {
                        arr[index] = val.trim();
                    });

                    // 获取buymoney / sellmoney  '<0.1' '11.5' '11.5k' '11.5m' 其他更大的数值
                    if (td_innerText_arr[0].indexOf("<") != -1) {
                        // td_value_obj.Buymoney = 0.1;
                        money = 0.1;
                    } else {
                        if (!isNaN(td_innerText_arr[0])) {
                            // td_value_obj.Buy
                            money = parseFloat(td_innerText_arr[0]);

                        } else {
                            for (let number_char of number_chars_arr) {
                                if (td_innerText_arr[0].indexOf(number_char) != -1) {
                                    money = parseFloat(td_innerText_arr[0]) * 10 ** number_chars_obj[number_char];
                                }
                            }

                        }

                    }
                    let temp_td_innerText = td_innerText_arr.pop();
                    let temp_td_innerText_arr = temp_td_innerText.split("/");
                    td_innerText_arr = [...td_innerText_arr, ...temp_td_innerText_arr];
                    td_innerText_arr.forEach((val, index, arr) => {
                        arr[index] = val.trim();
                    });
                    console.log("td_innerText_arr=", td_innerText_arr);

                    //获取buyamount sellamount

                    for (let number_char of number_chars_arr) {
                        // 如果有k , m 等 需要转化为字符串
                        if (td_innerText_arr[1].indexOf(number_char) != -1) {
                            amount = String(parseInt(parseFloat(td_innerText_arr[1])) * 1000) + '0'.repeat(number_chars_obj[number_char] - 3);
                            break;
                        }
                    }
                    if (amount === 0) {
                        amount = parseFloat(td_innerText_arr[1]);

                    }


                    // 获取buycount  1 txns
                    td_innerText_arr[2] = td_innerText_arr[2].split(" ")[0].trim();
                    // td_value_obj.Buy
                    count = td_innerText_arr[2];

                    if (i == 2) {
                        td_value_obj.Buycount = count;
                        td_value_obj.Buymoney = money;
                        td_value_obj.Buyamount = amount;
                    } else if (i == 3) {
                        td_value_obj.Sellcount = count;
                        td_value_obj.Sellmoney = money;
                        td_value_obj.Sellamount = amount;
                    }


                }

            }
            td_value_obj.Earn = td_value_obj.Sellmoney - td_value_obj.Buymoney;
            td_value_obj.Earnper = td_value_obj.Buymoney == 0 ? -10 : td_value_obj.Earn / td_value_obj.Buymoney;

            if (typeof (td_value_obj.Sellamount) == 'string') {
                if (typeof (td_value_obj.Buyamount) == 'string') {
                    if (td_value_obj.Sellamount.length > td_value_obj.Buyamount.length) {
                        td_value_obj.Amountper = 10;
                    } else if (td_value_obj.Sellamount.length == td_value_obj.Buyamount.length) {
                        td_value_obj.Amountper = parseFloat(td_value_obj.Sellamount.slice(0, 2)) / parseFloat(td_value_obj.Buyamount.slice(0, 2));
                    } else {
                        td_value_obj.Amountper = 0.1;
                    }
                } else {
                    td_value_obj.Amountper = 10;
                }
            } else {
                if (td_value_obj.Sellamount == 0) {
                    td_value_obj.Amountper = 0;
                } else if (typeof (td_value_obj.Buyamount) == 'string') {
                    td_value_obj.Amountper = 0.1;
                }
                else {
                    td_value_obj.Amountper = td_value_obj.Buyamount == 0 ? -10 : parseFloat(td_value_obj.Sellamount) / parseFloat(td_value_obj.Buyamount);

                }
            }



            let td_value_arr = Object.values(td_value_obj);

            res.push(td_value_arr);

        }

    }
    function clickBotton() {
        // let table_div_ep1 = document.querySelector('.custom-19qkkht');
        let table_div_ep1 = document.getElementsByClassName('custom-p3e2vj')[0];
        let divscrollerdep2 = table_div_ep1.querySelector('[data-test-id="virtuoso-scroller"]');

        let div_table = table_div_ep1.getElementsByClassName('custom-17mi4hx')[0];
        // console.log("div_table=", div_table);
        let titlearr = get_thead_arr(div_table.children[0]);

        let urlpathname_arr = window.location.pathname.slice(1).split('/');

        res.push(titlearr);
        let tbody_arr = Array.from(div_table.children);
        tbody_arr.shift();
        get_tbodyarr(tbody_arr);

        res.forEach((val, index, arr) => { arr[index] = val.join() + "\n" });

        urlpathname_arr[0] = urlpathname_arr[0].slice(0, 3);

        funcDownload(res.join(""), "Dex-" + urlpathname_arr.join('-') + ".csv");


    }






})();
