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

// maker 降序
// https://dexscreener.com/new-pairs?rankBy=pairAge&order=asc&chainIds=solana&dexIds=raydium&minLiq=2000&minAge=4&maxAge=48&min24HTxns=900&min24HBuys=800&min24HSells=800&min24HChg=100

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


function getCurrentTime() {
    const zeroFill = (i) => {
        if (i >= 0 && i <= 9) {
            return "0" + i;
        } else {
            return '' + i;
        }

    }
    let date = new Date();//当前时间
    let year = date.getFullYear();
    let month = zeroFill(date.getMonth() + 1);//月
    let day = zeroFill(date.getDate());//日
    let hour = zeroFill(date.getHours());//时
    let minute = zeroFill(date.getMinutes());//分
    let second = zeroFill(date.getSeconds());//秒

    //当前时间
    var curTime = year + month + day + '_' + hour + minute + second;
    return curTime;
}


(async function () {

    await sleep(4000);
    console.log("enter ")
    var res = [];

    var mydivbox = document.createElement("div");
    //var input = document.createElement("input")
    var button = document.createElement("button");//创建一个按钮
    //mydivbox.appendChild(input);
    mydivbox.appendChild(button);
    //input.value = "350";
    //input.className = "tam-myinput"
    //input.type = "number"
    button.className = "tam-mybutton"
    button.textContent = "upstep"; //按钮内容
    button.style.width = "100px"; //按钮宽度
    button.style.height = "30px"; //按钮高度
    button.style.align = "center"; //文本居中
    button.style.color = "blue"; //按钮文字颜色
    button.style.background = "#e33e33"; //按钮底色
    button.style.border = "1px solid #e33e33"; //边框属性
    //button.style.borderRadius = "4px"; //按钮四个角弧度

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

    // var main_div = document.getElementsByTagName("main")[0];
    // chakra-button__group custom-1itqpek

    // var parent_div = main_div.getElementsByClassName("custom-12szi09")[0];
    // console.log("parent_div.getElementsByClassName", parent_div.getElementsByClassName("custom-1itqpek")[0])
    // parent_div.insertBefore(mydivbox, parent_div.getElementsByClassName("chakra-button__group")[0]);
    // parent_div.appendChild(mydivbox);
    document.body.appendChild(mydivbox)


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


    function clickBotton() {
        console.log("entere clickBotton");
        res = [];

        let table_div = document.querySelector('.ds-dex-table.ds-dex-table-new');
        // let theadtitles = table_div.querySelector('.ds-dex-table-th');
        // let titlearr = theadtitles.innerText.trim().split(/\r?\n/);
        let titlearr = ["TokenIdx", 'PairAddress', 'TokenName', 'QuoteToken', 'Age', "Buys", "Sells", "Makers", 'Liquidity', 'Fdv']
        res.push(titlearr);
        let tbodytrs_arr = table_div.getElementsByTagName('a');
        for (let i = 0; i < tbodytrs_arr.length; i++) {
            let tdtexts = []
            let tbodytr = tbodytrs_arr[i];
            let tds_arr = tbodytr.querySelectorAll('.ds-table-data-cell');
            let token_address = tbodytr.href.trim().split('/').pop();
            let token_idx = tbodytr.getElementsByClassName("ds-dex-table-row-badge-pair-no")[0].innerText.trim().replace(/#/g, '');
            let token_name = tbodytr.getElementsByClassName('ds-dex-table-row-base-token-symbol')[0].innerText.trim();
            let quote_token = tbodytr.getElementsByClassName('ds-dex-table-row-quote-token-symbol')[0].innerText.trim();
            let pair_age = tbodytr.getElementsByClassName('ds-dex-table-row-col-pair-age')[0].innerText.trim();

            let pair_buys = tds_arr[3].innerText.trim().replace(/,/g, '');
            let pair_sells = tds_arr[4].innerText.trim().replace(/,/g, '');
            let pair_makers = tds_arr[6].innerText.trim().replace(/,/g, '');
            let pair_liquidity = tds_arr[tds_arr.length - 2].innerText.trim().replace(/[$]/, '');
            let pair_fdv = tds_arr[tds_arr.length - 1].innerText.trim().replace(/[$]/g, '');

            tdtexts = [token_idx, token_address, token_name, quote_token, pair_age, pair_buys, pair_sells, pair_makers, pair_liquidity, pair_fdv];
            res.push(tdtexts);
        }


        res.forEach((val, index, arr) => { arr[index] = val.join() + "\n" });
        let curTime = getCurrentTime();
        let urlpathname = window.location.pathname.slice(1).split('/').pop();
        urlpathname = urlpathname.replaceAll('-', "_");


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



    }



})();


