class AsinChecker {

    constructor() {

        this.timer = null;
        this.checkedAsins = new Map();
        this.publishButton = document.getElementById('publish');

    }

    startChecking(interval) {

        this.timer = setInterval(() => {
            this.findAmazonLinks();
        }, interval);
    }

    stopChecking() {

        clearInterval(this.timer);

    }

    findAmazonLinks() {

        var content = tinyMCE.activeEditor.getContent({ format: 'text' });
        if (content) {
            const regex = /https?:\/\/www\.amazon\.it\/dp\/([a-zA-Z0-9]+)/g;
            let match;
            let asins = [];
            while ((match = regex.exec(content)) !== null) {
                asins.push(match[1]);
            }
            
            this.checkAsins(asins);
             
        }
    }

    async checkAsins(asins) {
        
        var post_ID = (document.getElementById("post_ID")) ? document.getElementById("post_ID").value : 0;

        for (let i = 0; i < asins.length; i++) {
            if (!this.checkedAsins.has(asins[i])) {
                let api_call = `/wp-json/api/v1/articlesbyasin/${asins[i]}/${typenow}/${post_ID}/`;
                //console.log("api_call", api_call);
                let response = await fetch(api_call);
                let validAsin = await response.json();
        
                this.checkedAsins.set(asins[i],  (validAsin.length > 0) ? validAsin[0].title : false);
            }
        }

        this.checkWarning(asins);

    }

    checkWarning(asins) {
        
        //console.log("this.checkedAsins", this.checkedAsins);
        const validAsins = asins.filter(asin => this.checkedAsins.has(asin) && this.checkedAsins.get(asin) !== false);
        
        if (validAsins.length > 0) {
            const validAsin = validAsins[0]; // Prendiamo solo il primo asin valido
            const validTitle = this.checkedAsins.get(validAsin);
            this.showWarning(validAsin, validTitle);
            //this.disablePublish();
        } else {
            this.hideWarning();
            //this.enablePublish();
        }
    }

    hideWarning() {

        if (document.getElementById("notice-warning-asin")) document.getElementById("notice-warning-asin").remove();

    }

    showWarning(asin, titolo) {

        if (!document.getElementById("notice-warning-asin")){

            const warning = document.createElement("div");
            warning.setAttribute("class", "acf-notice -error acf-error-message");
            warning.setAttribute("id", "notice-warning-asin");
            warning.innerHTML = `<p>Attenzione: il prodotto che stai inserendo è già stato pubblicato oggi: ${titolo}</p>`;

            const titleDiv = document.getElementById("titlediv");
            titleDiv.insertAdjacentElement('beforebegin', warning); // Inserisce il warning sopra l'elemento con id "titlediv"
        
        }

    }

    disablePublish() {

        if (this.publishButton) {
            this.publishButton.disabled = true;
        }

    }

    enablePublish() {

        if (this.publishButton) {
            this.publishButton.disabled = false;
        }

    }

}

document.addEventListener('DOMContentLoaded', function () {
    // Utilizzo della classe
    const asinChecker = new AsinChecker();
    asinChecker.startChecking(1000); // Avvia il controllo ogni secondo
});
