// ==UserScript==
// @name         defi-GetTran-SOL
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       You
// @match        https://www.defined.fi/sol/*
// @icon         https://www.google.com/s2/favicons?sz=64&domain=tampermonkey.net
// @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 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() {

    // let titlearr = _thead.innerText.trim().split(/\r?\n/);
    let titlearr = ['TYPE', 'DATE', 'PRICE', 'USD', 'SOL', 'Token', 'MAKER', 'TXN'];
    return titlearr;
}



var pre_timestamp = -1;
var now_timestamp = -1;
async function get_tbody_data() {
    // let interval;
    // let timeout;
    // let equaltimes = 0
    // let dataindex;
    let tbody = document.querySelector("div.ReactVirtualized__Grid__innerScrollContainer");

    let tbodytrs;
    tbodytrs = tbody.children;
    let style_top = parseInt(parseFloat(tbodytrs[0].style.top.replace("px", "")));
    cur_firdataindex = parseInt(style_top / 40);



    let curpos = getted_dataindex - cur_firdataindex + 1;

    console.log("get_tbody_data curpos=", curpos, "tbodytrs.len=", tbodytrs.length, "res_data.len=", res_data.length, "cur_firdataindex=", cur_firdataindex, "getted_dataindex=", getted_dataindex,)
    let getted_style_top = parseInt(parseFloat(tbodytrs[tbodytrs.length - 1].style.top.replace("px", "")));
    getted_dataindex = parseInt(getted_style_top / 40);

    for (let i = curpos; i < tbodytrs.length; i++) {
        // dataindex--;
        let arr_tds;
        while (true) {
            try {
                arr_tds = Array.from(tbodytrs[i].children[0].children);
                break;
            } catch (err) {
                await sleep(150);
            }
        }

        let tdtexts = [];
        if (arr_tds.length != 8) {
            continue;
        }
        for (let i = 0; i < arr_tds.length; i++) {
            if (i == 0) {

                let type = "no";
                let computeStyle = window.getComputedStyle(arr_tds[i].children[0], null);
                let color = computeStyle.color.trim();
                if (color == "rgb(241, 152, 159)") {
                    type = "Sell"
                }
                else if (color == "rgb(161, 219, 177)") {
                    type = "Buy"
                }
                tdtexts.push(type);
            }
            else if (i == 1) {
                //date
                let month, day, hour, minute, second;
                let str_date = "2024 " + arr_tds[i].innerText.trim()
                let cur_date = new Date(str_date);
                let timestamp = cur_date.valueOf() / 1000;
                if (pre_timestamp == -1) {
                    pre_timestamp = timestamp;

                }
                now_timestamp = timestamp
                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];
                let str_utctime = "2024-" + month + "-" + day + " " + hour + ":" + minute + ":" + second;

                tdtexts.push(str_utctime);
            } else if (i == 2) {
                // price
                let str_price = ""
                let arr_span_price = Array.from(arr_tds[i].querySelector("span").children);
                arr_span_price.shift();
                if (arr_span_price.length == 1) {
                    str_price = arr_span_price[0].innerText.trim().replace(/[(\$)<,]/g, "").trim();
                } else {
                    let str_zero_repeat = arr_span_price[1].children[0].innerText.trim();
                    let fir_price = arr_span_price[0].innerText.trim().replace(/[(\$)<,]/g, "");
                    let sec_price = arr_span_price[1].innerText.trim().replace(/[(\$)<,]/g, "");
                    sec_price = sec_price.replace(str_zero_repeat, "")
                    sec_price = "0".repeat(parseInt(str_zero_repeat) - 1) + sec_price;
                    str_price = fir_price + sec_price;
                }
                // let usdstr = arr_tds[i].innerText.trim().replace(/[(\$)<,]/g, "");
                tdtexts.push(str_price);
            } else if (i == 3) {
                // usd
                let usdstr = arr_tds[i].innerText.trim().replace(/[(\$)<,]/g, "").trim();
                tdtexts.push(usdstr);
            } else if (i == 4) {
                // sol
                let str_sol;
                let arr_span_sol = Array.from(arr_tds[i].querySelector("span").children);

                if (arr_span_sol.length == 1) {
                    str_sol = arr_span_sol[0].innerText.trim().replace(/[(\$)<,]/g, "").trim();
                } else {
                    str_sol = "0";
                }

                tdtexts.push(str_sol);
            } else if (i == 5) {
                // Token
                // tdtexts.push(arr_tds[i].innerText.trim().replace(/[(\$)<,]/g, ""));

                let str_token_amount = arr_tds[i].innerText.trim().replace(/[(\$)<,]/g, "").trim();
                str_token_amount = str_token_amount.replace(/\s+/g, "");

                str_token_amount = str_token_amount.toLowerCase();
                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 >= 6) {
                let url_para = arr_tds[i].querySelector("a").href.split('/').pop();
                tdtexts.push(url_para);

            }

        }

        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 + "_raydium" + "_" + parseInt(Date.now() / 1000) + ".csv");
    res_data = [];

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

    cur_firdataindex = 0;
    getted_dataindex = -1;

    let interval;

    let equaltimes = 0
    let dataindex, totaldataindex;
    let tbody = document.querySelector("div.ReactVirtualized__Grid__innerScrollContainer");


    async function notimeoutup() {
        console.log("enter notimeoutup")


        console.log('reslen totalindex', res_data.length, totaldataindex);

        save_resdata();
    }

    async function down() {
        interval = setInterval(async () => {
            // let sTop = element.scrollTop;

            let tbodytrs;
            let arr_tds;
            if (sTop != 0 && sTop == element.scrollTop) {
                equaltimes++;
                if (equaltimes > 1) {
                    console.log("equaltimes=", equaltimes);
                }

                await sleep(250);

                if (equaltimes >= 30) {
                    clearInterval(interval);
                    tbodytrs = tbody.children;
                    // dataindex = parseInt(tbodytrs[tbodytrs.length - 1].getAttribute('data-index'));
                    let style_top = parseInt(parseFloat(tbodytrs[tbodytrs.length - 1].style.top.replace("px", "")));
                    dataindex = parseInt(style_top / 40);
                    totaldataindex = dataindex;
                    console.log('totaldataindex', totaldataindex);
                    try {
                        // arr_tds = Array.from(tbodytrs[0].getElementsByTagName("td")[0].children);
                        arr_tds = Array.from(tbodytrs[0].children[0].children);
                    } catch (err) {
                        await sleep(100);
                        // arr_tds = Array.from(tbodytrs[0].getElementsByTagName("td")[0].children);
                        arr_tds = Array.from(tbodytrs[0].children[0].children);
                    }
                    let cur_date = new Date(arr_tds[1].innerText.trim());
                    console.log("cur_date=", cur_date);
                    notimeoutup();
                }
            } else {
                equaltimes = 0;
                sTop = element.scrollTop;

            }
            await get_tbody_data();
            if (res_data.length % 5000 <= 150) {
                console.log("save_resdata last_element= ", res_data[res_data.length - 1])
            }
            if (res_data.length >= 8000 && now_timestamp - pre_timestamp >= 1800) {
                pre_timestamp = -1;
                now_timestamp = -1;
                save_resdata();
                await sleep(3000);
            }



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

    }

    down()

}



var res_data = [];
var cur_firdataindex = 0;
var getted_dataindex = -1;
var sTop = 0;
// 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_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"; //边框属性
    button_tran.addEventListener("click", clickButton); //监听按钮点击事件

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




    async function clickButton() {
        res_data = [];
        cur_firdataindex = 0;
        getted_dataindex = -1;

        console.log("enter clickButton res_data=", res_data);
        let divscrollerdep2 = document.querySelector('[aria-label="grid"]');

        var table_ = document.querySelector("div.MuiBox-root.css-2povsm");

        let titlearr = get_thead_arr();
        res_data.push(titlearr);
        autoScroll(divscrollerdep2, 1);
    }

})();




