// ==UserScript==
// @name         DexScreen-GetTran-HasStartDate
// @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 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 = ['DATE', 'TYPE', 'USD', 'Token', 'SOL', 'PRICE', 'MAKER', 'TXN'];
    return titlearr;
}





function handletime(res) {


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




}


function autoScroll(downstep, upstep, element, tbody, indexstart, startdate_timestamp) {

    let interval;
    let timeout;
    let equaltimes = 0
    let dataindex, totaldataindex;

    async function notimeoutup(upstep) {
        console.log("enter notimeoutup")
        let tbodytrs = tbody.querySelectorAll('tr[class*="custom-"]');
        let firdataindex = parseInt(tbodytrs[0].getAttribute('data-index'));
        let print_idx = 0;
        while (firdataindex >= indexstart) {
            print_idx++;
            tbodytrs = tbody.querySelectorAll('tr[class*="custom-"]');
            firdataindex = parseInt(tbodytrs[0].getAttribute('data-index'));
            if (print_idx % 30 == 0) {
                console.log("firdataindex,dataindex", firdataindex, dataindex);
            }

            let curpos = dataindex - 1 - firdataindex;
            for (let i = curpos; i >= 0; i--) {
                dataindex--;
                let arr_tds;
                while (true) {
                    try {
                        arr_tds = Array.from(tbodytrs[i].getElementsByTagName("td")[0].children);
                        break;
                    } catch (err) {
                        await sleep(150);
                    }
                }

                let tdtexts = [];
                for (let i = 0; i < arr_tds.length; i++) {
                    if (i == 0) {
                        //date
                        //title 01:36:59, Saturday, February 4, 2023
                        //text Feb 4 10:54:35 PM
                        //有bug 12AM 为凌晨0点 -12  12PM就是中午12
                        let month, day, hour, minute, second, isPM;
                        let cur_date = new Date(arr_tds[0].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)



                        //if want UTCtimestamp
                        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());

                    } else if (i == 5) {
                        if (arr_tds[5].querySelectorAll("span").length == 2) {
                            tdtexts.push(arr_tds[5].querySelector("span").title.trim().replace(/[(\$),]/g, ""));
                            // simtdtexts.push(tds[5].querySelector("span").title.trim().replace(/[(\$),]/g, ""));

                        } else {
                            tdtexts.push(arr_tds[i].innerText.trim().replace(/[(\$),]/g, ""));
                            // simtdtexts.push(tds[i].innerText.trim().replace(/[(\$),]/g, ""));
                        }

                    } else if (i == 2) {
                        let usdstr = arr_tds[i].innerText.trim().replace(/[(\$)<,]/g, "");
                        if (usdstr == '-') usdstr = '0';
                        tdtexts.push(usdstr);

                    } else {
                        //make $ , replace ''
                        tdtexts.push(arr_tds[i].innerText.trim().replace(/[(\$)<,]/g, ""));

                    }


                }

                res.push(tdtexts);

            }
            // element.scrollTop -= upstep;
            tbodytrs[0].scrollIntoView({ behavior: "smooth", block: "end" });
            await sleep(200);
        }

        console.log('reslen totalindex', res.length, totaldataindex);
        res = handletime(res);
        res.forEach((val, index, arr) => { arr[index] = val.join() + "\n" });

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

        funcDownload(res.join(""), urlpathname + "_raydium" + ".csv");


    }

    function down() {
        interval = setInterval(async () => {
            let sTop = element.scrollTop;
            element.scrollTop += downstep;
            let tbodytrs;
            if (sTop == element.scrollTop) {
                equaltimes++;
                console.log("equaltimes=", equaltimes)
                await sleep(300);
                if (startdate_timestamp != 0) {
                    return;
                }
                if (equaltimes >= 20) {
                    clearInterval(interval);
                    tbodytrs = tbody.querySelectorAll('tr[class*="custom-"]');
                    dataindex = parseInt(tbodytrs[tbodytrs.length - 1].getAttribute('data-index'));
                    totaldataindex = dataindex;
                    console.log('totaldataindex', totaldataindex);
                    try {
                        arr_tds = Array.from(tbodytrs[0].getElementsByTagName("td")[0].children);
                    } catch (err) {
                        await sleep(100);
                        arr_tds = Array.from(tbodytrs[0].getElementsByTagName("td")[0].children);
                    }
                    let cur_date = new Date(arr_tds[0].innerText.trim());
                    console.log("cur_date=", cur_date);
                    notimeoutup(upstep);
                }
            } else {
                equaltimes = 0;
                tbodytrs = tbody.querySelectorAll('tr[class*="custom-"]');
                let arr_tds;
                try {
                    arr_tds = Array.from(tbodytrs[0].getElementsByTagName("td")[0].children);
                } catch (err) {
                    await sleep(100);
                    arr_tds = Array.from(tbodytrs[0].getElementsByTagName("td")[0].children);
                }
                let cur_date = new Date(arr_tds[0].innerText.trim());

                if (cur_date.valueOf() >= startdate_timestamp) {
                    return;
                }
                console.log("startate=", cur_date);
                clearInterval(interval);
                await sleep(2000);
                tbodytrs = tbody.querySelectorAll('tr[class*="custom-"]');
                dataindex = parseInt(tbodytrs[tbodytrs.length - 1].getAttribute('data-index'));
                totaldataindex = dataindex;
                console.log('totaldataindex', totaldataindex);
                notimeoutup(upstep);
            }
        }, 1300)

    }

    down()

}



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 input = document.createElement("input")
    var input_startdate = document.createElement("input")
    var button_tran = document.createElement("button");//创建 获取toptran一个按钮
    mydivbox.appendChild(input);
    mydivbox.appendChild(input_startdate);
    mydivbox.appendChild(button_tran);

    input.value = "300";
    input.className = "tam-myinput";
    input.type = "number";
    input.style.width = "80px";

    input_startdate.value = "0101-0000";
    input_startdate.className = "tam-myinput-startdate";
    input_startdate.type = "text";
    input_startdate.style.width = "80px";

    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";


    function clickButton() {
        res = [];
        console.log("enter clickButton res=", res);

        let arr_urlpathname = window.location.pathname.slice(1).split('/');
        // let table_div_ep1 = document.getElementsByClassName('custom-p3e2vj')[0];
        // let divscrollerdep2 = table_div_ep1.querySelector('[data-testid="virtuoso-scroller"]');
        let divscrollerdep2 = document.querySelector('[data-testid="virtuoso-scroller"]');

        var table_ = document.getElementsByTagName("table")[0];

        let thead_ = table_.getElementsByTagName('thead')[0];
        let titlearr = get_thead_arr(thead_);
        res.push(titlearr);
        let tbody_ = table_.getElementsByTagName('tbody')[0];
        // let tbody_ = document.getElementsByClassName('custom-p3e2vj')[0].getElementsByTagName('table')[0].getElementsByTagName('tbody')[0];
        let upstep = parseInt(input.value);
        let startdate_timestamp = 0;
        if (input_startdate.value.trim() == "0101-0000") {
            ;
        } else {
            let cur_month = input_startdate.value.trim().slice(0, 2);
            let cur_day = input_startdate.value.trim().slice(2, 4);
            let cur_hour = input_startdate.value.trim().slice(5, 7);
            let cur_minute = input_startdate.value.trim().slice(7, 9);
            console.log("date", cur_month + "-" + cur_day + " " + cur_hour + ":" + cur_minute + ":" + "00");
            startdate_timestamp = new Date(cur_month + "-" + cur_day + " " + cur_hour + ":" + cur_minute + ":" + "00").valueOf();

        }
        console.log(upstep, startdate_timestamp);

        autoScroll(7000, upstep, divscrollerdep2, tbody_, 30, startdate_timestamp);
    }

})();




