// ==UserScript==
// @name         Get_Tran_Pump
// @namespace    http://tampermonkey.net/
// @version      2024-07-14
// @description  try to take over the world!
// @author       You
// @match        https://pump.fun/*
// @icon         https://www.google.com/s2/favicons?sz=64&domain=pump.fun
// @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 monthmatch = {
    "January": "01",
    "February": "02",
    "March": "03",
    "Apr": "04",
    "May": "05",
    "June": "06",
    "July": "07",
    "August": "08",
    "September": "09",
    "October": "10",
    "November": "11",
    "December": "12",
};

var number_chars_arr = ["k", "m", "b", "t", "p"];

function get_thead_arr(_thead) {

    let titlearr = _thead.innerText.trim().split(/\r?\n/);


    titlearr = ['MAKER', 'TYPE', 'SOL', 'Token', 'DATE', 'TXN'];
    return titlearr;
}





function handletime(res, date_idx) {

    for (let i = 1; i < res.length; i++) {
        let md = res[i][date_idx].slice(0, 2);
        let hms = res[i][date_idx].slice(2);
        res[i][date_idx] = md.join("-") + " " + hms.join(":");
    }
    return res;

}




async function down(element) {
    let equaltimes = 0;
    let downstep = 800;
    while (true) {
        let sTop = element.scrollTop;
        element.scrollTop += downstep;
        let tbodytrs;
        if (sTop == element.scrollTop) {
            equaltimes++;
            console.log("equaltimes=", equaltimes)
            await sleep(300);
            if (equaltimes == 5) {
                break;

            }
        }
    }
    return;


}

function get_tbody_data() {
    console.log("enter get_tbody_data");
    let div_table = document.querySelector("div.flex.flex-col.gap-2.w-2\\/3 > div.w-full.text-xs.sm\\:text-sm.text-gray-400.bg-transparent.rounded-lg ")
    let tbody = div_table.querySelectorAll("div.text-xs.my-1");

    let arr_tbodytrs = Array.from(tbody);

    for (let idx = 0; idx < arr_tbodytrs.length; idx++) {

        let arr_tds;
        arr_tds = Array.from(arr_tbodytrs[idx].children);
        if (idx % 100 == 0) {
            console.log("idx=", idx, arr_tbodytrs[idx])
        }

        let tdtexts = [];
        for (let i = 0; i < arr_tds.length; i++) {
            if (i == 0) {
                // maker
                // <a href="/profile/6Jf4iDyKGVY8CXynmHqrgUzGbx1GwerMyR2gZQ9LWFje">
                tdtexts.push(arr_tds[i].querySelector("a").href.split('/').pop());

            } else if (i == 1) {
                // type
                let type = arr_tds[i].innerText.trim();
                if (type == "buy") {
                    tdtexts.push("Buy");
                } else {
                    tdtexts.push("Sell");
                }


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

            } else if (i == 3) {
                // sol 
                tdtexts.push(arr_tds[i].innerText.trim());

            } else if (i == 4) {
                let str_token_amount = arr_tds[i].innerText.trim();
                let float_token_amount;
                float_token_amount = parseFloat(str_token_amount);

                for (let number_char of number_chars_arr) {
                    if (str_token_amount.indexOf(number_char) != -1) {
                        float_token_amount = parseFloat(str_token_amount) * 10 ** number_chars_obj[number_char];
                    }
                }
                tdtexts.push(float_token_amount);
            }
            else if (i == 5) {
                //date
                let month, day, hour, minute, second, isPM;
                let cur_date = new Date(arr_tds[i].innerText.trim());
                month = cur_date.getMonth() + 1;// Returns the month (0-11)
                day = cur_date.getDate();//Returns the day of the month (1-31)
                hour = cur_date.getHours(); // Returns the hour (0-23)
                minute = cur_date.getMinutes(); // Returns the minute (0-59)
                second = cur_date.getSeconds(); // Returns the second (0-59)

                let utctime = [month, day, hour, minute, second];


                tdtexts.push(utctime);
                // simtdtexts.push(utctime);

            } else if (i == 6) {
                tdtexts.push(arr_tds[i].querySelector("a").href.split('/').pop());

            }


        }

        res.push(tdtexts);

    }



}


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

(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.style.height = "28px"; //按钮高度
    button_tran.style.align = "center"; //文本居中
    button_tran.style.color = "blue"; //按钮文字颜色
    button_tran.style.background = "#e33e33"; //按钮底色
    button_tran.style.border = "1px solid #e33e33"; //边框属性

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

    mydivbox.style.position = "fixed";
    mydivbox.style.top = "60px";
    mydivbox.style.right = "40px";
    document.body.appendChild(mydivbox);
    // var theadtr = document.getElementsByClassName("custom-19qkkht")[0].getElementsByTagName("thead")[0];
    var theadtr = document.getElementsByTagName("table")[0].getElementsByTagName("thead")[0];
    theadtr.style.color = "blue";


    async function clickButton() {
        res = [];
        console.log("enter clickButton res=", res);
        // button_trades = document.querySelector("div.flex.gap-2.h-fit.mt-4").children[1];
        // await button_trades.click()


        let div_table = document.querySelector("   div.flex.flex-col.gap-2.w-2\\/3 > div.w-full.text-xs.sm\\:text-sm.text-gray-400.bg-transparent.rounded-lg ")

        let thead = div_table.querySelector("div:nth-child(2)");
        let button_date = thead.children[5].querySelector("button");
        await button_date.click();
        let titlearr = get_thead_arr(thead);
        res.push(titlearr);

        await sleep(1500);
        await down(element = document.documentElement);

        // div_page_selected = document.querySelector("div.w-full.flex.justify-center.mt-4  ").children[0];

        let pre_number_page = -1
        let number_click_page = 0;

        while (true) {



            div_page_selected = document.querySelector("div.justify-self-end.mb-20").children[0];
            let number_page = parseInt(div_page_selected.children[1].innerText);
            console.log("number_page=", number_page);
            if (pre_number_page == number_page) {
                number_click_page++;
                if (number_click_page >= 3) {

                    break;
                }

            } else {

                get_tbody_data();


            }
            let button_next = div_page_selected.children[2];
            pre_number_page = number_page
            await button_next.click();
            await sleep(2000);

        }
        let urlpathname = window.location.pathname.slice(1).split('/');
        console.log("urlpathname=", urlpathname)
        res = handletime(res, 4);
        res.forEach((val, index, arr) => { arr[index] = val.join() + "\n" });
        funcDownload(res.join(""), urlpathname + "_pump" + ".csv");



    }

})();




