const CACHEROOTLOCATION = 'https://site.classic-medallics.com/ytimes/dynamic-content/';
$(document).ready(function () {
    const query = `themes=air force`;
    if (query) {
        if(!document.getElementById('dynamicContentStyle')) {
            $("head").append(`
                
            `);
            $("#ytimesFilteredContent .contents").html("
Loading...
");
        }
        $("#ytimesFilteredContent .contents").addClass("loading");
        let cacheData = {
            "cmd": "r",
            "query": query
        }
        getCache(cacheData)
            .then(function(data) {
                if(data) {
                    console.log("Cache hit");
                    useData(data);
                } else {
                    loadData(query);
                }
            })
            .catch(function(data) {
                loadData(query);
            });
    } else {
        $("#ytimesFilteredContent .contents").removeClass("loading");
        console.log("query parameter is not found in the URL.");
    }
});
function loadData(query) {
    let url = `https://www.ytimes.net/catalog/store-folders/yhst-27505360700960/custom/query.php?query=${query}`;
    fetch(url)
        .then((response) => {
            if (!response.ok) {
                throw new Error(
                    `Network response was not ok: ${response.status}`
                );
            }
            return response.json(); // Parse the JSON response
        })
        .then((data) => {
            // Process the JSON data here
            if(typeof(data) == 'string') {
                $("#ytimesFilteredContent").prepend(data);
                $("#ytimesFilteredContent .contents").removeClass("loading");
            } else {
                writeCache(query, data);
                useData(data);
            }
        })
        .catch((error) => {
            $("#ytimesFilteredContent .contents").removeClass("loading");
            console.error("Error:", error);
        });
}
function useData(data) {
    YTIMES.pageObjects = data;
    $("#ytimesFilteredContent .contents").removeClass("loading");
    $("#ytimesFilteredContent .contents").html(buildPage(data));
    $("#ytimesFilteredContent .contents .item .image img").on("error", function() {
        if($(this).data("image")) {
            $(this).attr("src",$(this).data("image"));
            $(this).data("image",null);
            $(this).parents(".image").css(
                {
                    "display": "flex",
                    "flex-direction": "column",
                    "justify-content": "center",
                    "align-items": "center"
                }
            )
        }
    });
    $.getScript("https://www.ytimes.net/catalog/store-folders/yhst-27505360700960/custom/ytimes-filtered-contents.js?v=53");
}
function canShow() {
    try {
        return CheckPwd(GetCookie("passphrase"));
    } catch(e) {
        return true;
    }
}
async function getCache(data) {
    const url = `${CACHEROOTLOCATION}cache.php`;
return(null);
    try {
      const response = await fetch(url, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
      });
  
      if (response.ok) {
        return await response.json();
      } else {
        return null;
      }
    } catch (error) {
      return null;
    }
}
  
function writeCache(query, data) {
    const dataToSend = {
        "cmd" : "w",
        "query" : query,
        "data" : data
    }
    const jsonData = JSON.stringify(dataToSend);
    const url = `${CACHEROOTLOCATION}cache.php`;
    // Create a fetch request to send the data asynchronously
    fetch(url, {
        method: 'POST',
        body: jsonData,
        headers: {
            'Content-Type': 'application/json',
        },
    }).then(response => {
        if (response.ok) {
            console.log('Data sent to cache successfully.');
        } else {
            console.error('Failed to send data to cache.');
        }
    })
    .catch(error => {
        console.error('writeCache Error:', error);
    });
}
function buildPage(data) {
    let itemsContainer = '';
    const formatter = new Intl.NumberFormat('en-US', {
        style: 'currency',
        currency: 'USD',
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
      });
    data.forEach(element => {
        const CANBEPERSONALIZED = 2;
        const INIMAGEAREA = 1;
        const NOTINIMAGEAREA = 0;
        let priceBlock = '';
        if (canShow()) {
            priceBlock = element.sectionPrice;
        }
		let flags = '';
		if ( typeof(element.new) != 'undefined' && element.new == 1 ) {
			flags += 'New';
		}
		if ( typeof(element.onsale) != 'undefined' && element.onsale == 1 ) {
			flags += 'Sale';
		}
		if ( typeof(element.closeout) != 'undefined' && element.closeout == 1 ) {
			flags += 'Clearance';
		}
		if ( typeof(element.orderable) != 'undefined' && element.orderable == 0 ) {
			flags += 'Out of Stock';
		}
		if ( typeof(element.discontinued) != 'undefined' && element.discontinued == 1 ) {
			flags += 'Discontinued';
		}
		if ( typeof(element.promo) != 'undefined' && element.promo == 1 ) {
			flags += 'Promo Offer';
		}
		flags += '
';
        itemsContainer += `
            
                
                    
                        
                    
					${flags}
                
 
                
                ${priceBlock}
            
 `;
    });
    return itemsContainer;
}