// ==UserScript==
// @name         DexScreen-GetTran
// @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 objcsv = {
    "tokenname": null,
    "res": null,
    "simres": null,
    "msimrs": null,

}
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, 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;

}



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

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


    //回调time相关
    let myDelay = 1000;
    let thisDelay = 1000;
    let start = Date.now();

    async function notimeoutup(upstep) {

        let tbodytrs = tbody.querySelectorAll('tr[class*="custom-"]');
        let firdataindex = parseInt(tbodytrs[0].getAttribute('data-index'));

        while (firdataindex >= indexstart) {
            tbodytrs = tbody.querySelectorAll('tr[class*="custom-"]');
            firdataindex = parseInt(tbodytrs[0].getAttribute('data-index'));

            console.log("firdataindex,dataindex", firdataindex, dataindex);

            let curpos = dataindex - 1 - firdataindex;
            for (let i = curpos; i >= 0; i--) {

                dataindex--;
                let arr_tds;
                try {
                    arr_tds = Array.from(tbodytrs[i].getElementsByTagName("td")[0].children);

                } catch (err) {
                    await sleep(100);
                    arr_tds = Array.from(tbodytrs[i].getElementsByTagName("td")[0].children);
                }

                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;
                        isPM = arr_tds[0].innerText.includes("PM");
                        let arr_dateinfo = arr_tds[0].innerText.trim().split(" ");
                        //y,m,d concat,

                        [hour, minute, second] = arr_dateinfo[2].trim().split(':');
                        // arr_dateinfo[2] = arr_dateinfo[2].trim().split(" ");
                        month = monthmatch[arr_dateinfo[0]];
                        day = arr_dateinfo[1];
                        if (hour == "12") {
                            if (!isPM) {
                                hour = "00";
                            }
                        } else if (isPM) {
                            hour = (parseInt(hour) + 12).toString();
                        }

                        //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;
            await sleep(200);
        }

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

        let urlpathname = window.location.pathname.slice(1).split('/');
        urlpathname[0] = urlpathname[0].slice(0, 3);

        // funcDownload(res.join(""), "Dex-" + objcsv.tokenname + "-" + urlpathname.join('-') + ".csv");
        funcDownload(res.join(""), "Dex_" + 'tran_' + urlpathname.join('_') + ".csv");


    }

    function down() {
        interval = setInterval(() => {
            let sTop = element.scrollTop;
            element.scrollTop += downstep;
            if (sTop == element.scrollTop) {
                equaltimes++;
                if (equaltimes == 5) {
                    clearInterval(interval);
                    let tbodytrs = tbody.querySelectorAll('tr[class*="custom-"]');
                    dataindex = parseInt(tbodytrs[tbodytrs.length - 1].getAttribute('data-index'));
                    totaldataindex = dataindex;
                    console.log('totaldataindex', totaldataindex);

                    notimeoutup(upstep);
                }
            }
        }, 1500)

    }

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

    input.value = "350";
    input.className = "tam-myinput"
    input.type = "number"

    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", clickBotton); //监听按钮点击事件

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


    function clickBotton() {
        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-test-id="virtuoso-scroller"]');
        let table_ = table_div_ep1.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 upstep = parseInt(input.value);
        console.log(upstep);
        //ori titlearr = ['DATE', 'TYPE', 'USD', 'Token', 'SOL', 'PRICE', 'MAKER', 'TXN'];
        //changeto titlearr = ['DATE', 'TYPE', 'USD', 'Token', 'MAKER', 'TXN'];




        autoScroll(7000, upstep, divscrollerdep2, tbody_, 80);
    }

})();
