// ==UserScript==
// @name         Dex-Filter-ListenToken-Long-SOL
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       You
// @match        https://dexscreener.com/new-pairs?rankBy=txns&order=desc&chainIds=solana&dexIds=raydium&minLiq=8000&minAge=48&min24HTxns=300&min24HBuys=100&min1HChg=4&min5MChg=2
// @icon         https://www.google.com/s2/favicons?sz=64&domain=tampermonkey.net
// @grant        none

// ==/UserScript==

// https://dexscreener.com/new-pairs?rankBy=txns&order=desc&chainIds=solana&dexIds=raydium&minLiq=8000&minAge=48&min24HTxns=300&min24HBuys=100&min1HChg=4&min5MChg=2

// dex_long_token

function funcDownload(content, filename) {
    // 创建隐藏的可下载链接
    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 number_chars_arr = ["k", "m", "b", "t", "p"];


let obj_pairaddress = {
    // "str_pairaddress": {
    //     "save_timestamp": 0,


    // }

}

var pre_click_timestamp = 0;

var now_timestamp = 0;

function click_avoid_sleep() {
    if (now_timestamp - pre_click_timestamp >= 2 * 60 * 1000) {
        pre_click_timestamp = now_timestamp;
        let th = document.querySelector("div.ds-dex-table-th");

        let button_click = th.children[5].querySelector("button");
        button_click.click();
    }



}



async function get_tbody_data() {
    let tbody = document.querySelector("div.ds-dex-table.ds-dex-table-new");

    let arr_tbody_trs = Array.from(tbody.querySelectorAll("a"));


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

        let a_element = arr_tbody_trs[idx];
        let pair_url = a_element.href;
        let pair_address = pair_url.split("/").pop();



        let arr_tds = Array.from(a_element.children);

        let tdtexts = [];

        tdtexts.push((Date.now()))
        tdtexts.push(pair_address);
        set_now_pairaddress.add(pair_address);

        for (let i = 0; i < arr_tds.length; i++) {
            if (i == 1) {
                //  price
                let price = arr_tds[i].innerText.trim().replace(/[(\$),]/g, "");
                tdtexts.push(price);

            } else if (i >= 7 && i <= 10) {
                // 5m 1h 6h 24h change

                let price_change = arr_tds[i].innerText.trim().replace(/[%,]/g, "");
                for (let number_char of number_chars_arr) {
                    if (price_change.indexOf(number_char) != -1) {
                        price_change = parseFloat(price_change) * 10 ** number_chars_obj[number_char];
                    }
                }

                tdtexts.push(price_change);
            }

        }

        arr_res_data.push(tdtexts);


    }
    now_timestamp = Date.now();
    click_avoid_sleep();
    save_resdata();

}

function drop_outtime_pairaddress() {
    // 距离上次save_timestamp 超过5分钟 删除

    let arr_pre_pairaddress = Object.keys(obj_pairaddress);

    for (let pre_pairaddress of arr_pre_pairaddress) {
        let pre_pairaddress_save_timestamp = obj_pairaddress[pre_pairaddress]["save_timestamp"];
        // 获取此pair已有5分钟 删除 掉此pair，允许再次获取新的
        if (now_timestamp - pre_pairaddress_save_timestamp > 5 * 60 * 1000) {
            delete obj_pairaddress[pre_pairaddress];

        }
    }

}


function save_resdata() {
    // console.log("enter save_resdata");
    drop_outtime_pairaddress();

    let set_intersection_pairaddress = new Set([...set_now_pairaddress].filter(value => set_pre_pairaddress.has(value)));


    // console.log("set_intersection_pairaddress=", set_intersection_pairaddress, 'set_pre_pairaddress=', set_pre_pairaddress, "set_now_pairaddress=", set_now_pairaddress);
    set_pre_pairaddress.clear();
    set_pre_pairaddress = set_now_pairaddress;
    set_now_pairaddress = new Set();


    if (set_intersection_pairaddress.size == 0) {
        return;
    }


    let temp_arr_res_data = arr_res_data;
    // console.log("temp_arr_res_data=", temp_arr_res_data);
    arr_res_data = [];

    for (let it of temp_arr_res_data) {
        let str_pairaddress = it[1];

        if (!set_intersection_pairaddress.has(str_pairaddress)) {
            continue;
        }
        else if (obj_pairaddress[str_pairaddress] != undefined) {
            continue;
        } else {

            obj_pairaddress[str_pairaddress] = {

                "save_timestamp": now_timestamp,
            }
            arr_res_data.push(it);
        }

    }



    if (arr_res_data.length == 0) {
        // res 为空
        // console.log("arr_res_data length is 0");
        return;
    }

    // console.log("arr_res_data=", arr_res_data)
    arr_res_data.unshift(["timestamp", "pairaddress", "price", "5m", "1h", "6h", "24h"]);

    arr_res_data.forEach((val, index, arr) => { arr[index] = val.join() + "\n" });

    let str_cur_time = "" + Date.now();


    funcDownload(arr_res_data.join(""), str_cur_time + "_long" + ".csv");
    arr_res_data = [];

}

function autoScroll() {
    console.log("enter autoScroll");
    async function fetchData() {
        await get_tbody_data();
        setTimeout(fetchData, 15 * 1000);
    }

    setTimeout(fetchData, 15 * 1000);

}


var arr_res_data = [];
var set_pre_pairaddress = new Set();
var set_now_pairaddress = new Set();
// window.addEventListener('load', () => {

(async function () {
    console.log("enter load");
    await sleep(6000);
    autoScroll();


})();




