//================== Stats table carets ===============================================
// The aeronet stats table changes the position/index of the regions when they
// are clicked, so we cannot easily assign a class to the regions that will maintain on click,
// so we must remove the carets on click, and then add them back after the table has finished

// changing its state

// ADD FUNCTION TO WAIT FOR TABLE TO FINISH CHANGING
function waitForMutation(selector, func) {
    return new Promise(resolve => {
        if (document.querySelector(selector)) {
            return resolve(document.querySelector(selector));
        };
        const observer = new MutationObserver(mutations => {
            if (document.querySelector(selector)) {
                resolve(document.querySelector(selector));
		// console.log(mutations);
		func(mutations);
	    }
        });
        observer.observe(document.body, {
            childList: true,
            subtree: true,
	    attributeOldValue: true, 
	    characterDataOldValue: true
        });
    });
}

// FIND THE REGIONS TO REMOVE THE CARETS BEFORE FLIPPING THEM
function targetRegions(mutations) {
    // Carets will populate in the wrong rows after click, so we must remove them
    for (const element of mutations) {
	if (['Mediterranean','NAfrica', 'MiddleEast'].includes(element.oldValue)) {
	    // Get elements parent node 2 above as it contains the target class
	    const target = element.target.parentNode.parentNode;
	    target.classList.remove('table_caret_up');
	    target.classList.remove('table_caret_down');
	};
    }
    // Now add the carets back in where appropriate
    flipCarets();
}

// CREATE FUNCTION TO FIND REGIONS AND FLIP CARETS AS NEEDED
function flipCarets() {
    var areas = "td:contains('Europe'), td:contains('Mediterranean'),td:contains('NAfrica'),td:contains('MiddleEast')";
    $(areas).addClass('table_caret_down');
    // Each table has the four regions. Split the returned areas into tables, and then address caret flips
    for(var i = 0; i < ($(areas).length/4); i++){
	var medIndex = parseInt($("td:contains('Mediterranean')").eq(i).attr('data-dash-row'));
	var nafricaIndex = parseInt($("td:contains('NAfrica')").eq(i).attr('data-dash-row'));
	var middleEastIndex = parseInt($("td:contains('MiddleEast')").eq(i).attr('data-dash-row'));
	var totalIndex = parseInt($("td:contains('Total')").eq(i).attr('data-dash-row'));
	// Ror each table, check if the caret should be flipped
	// if the next region is not at the next index, the dropdown is open 
	// trigger the caret to be flipped
	if (medIndex !== 1) {
	    $("td:contains('Europe')").eq(i).addClass('table_caret_up');
	};
	if ((medIndex + 1) !== middleEastIndex) {
	    $("td:contains('Mediterranean')").eq(i).addClass('table_caret_up');
	};
	if ((middleEastIndex + 1) !== nafricaIndex) {
	    $("td:contains('MiddleEast')").eq(i).addClass('table_caret_up');
	};
	if ((nafricaIndex + 1) !== totalIndex) {
	    $("td:contains('NAfrica')").eq(i).addClass('table_caret_up');
	};
    };
};

// ADD FUNCTION TO WAIT FOR CLICKS ON AREAS THAT SHOULD TRIGGER CARET FLIPS
$(document).ready(function () {
    $(document).on('click', "td:contains('Europe'), td:contains('Mediterranean'),td:contains('NAfrica'),td:contains('MiddleEast'), #scores-apply, #evaluation-tab", function () {
	waitForMutation('td.dash-cell.column-0', targetRegions);
    })
})
