// ROUTING FUNCTIONS

import { getDate } from './js_ines_core/router.js';
import { sendURL } from './js_ines_core/router.js';


// LISTEN FOR MESSAGES FROM CMS
window.addEventListener("message", (event) => {
    // Create list of addresses
    const hosts = [
	'http://bscesdust02.bsc.es',
	'https://dust.aemet.es',
	'https://dust02.bsc.es',
	'https://dust03.bsc.es'
    ];
    if (hosts.includes(event.origin)){
	console.log('DASH: Success!! ' + event.data);
	window.history.pushState("From Dashboard", "", event.data);
	return;
    }else{
	console.log('DASH: that is not the right address' + event.origin);
	return;
    }
}, false);

// GET THE VARIABLE VALUE
function getVar() {
	curvar = document.querySelector('.Select-value-label').innerHTML;
	curvar = curvar.split(' ').join('_')
	return 'var=' + curvar.toLowerCase() + '&';	
}

// GET MODELS CHECKED
function getModels(){
    const data = [...document.querySelectorAll('.form-check-input:checked')].map(e => e.value);
    data.forEach(function(item, index){
	this[index] = 'model=' + item
    }, data);		
    return data.join('&');
}

// CREATE URL WHEN MODELS-APPLY IS CLICKED
function handleModelsApply () {
	curvar = getVar()
	models = getModels()
	outputDate = getDate();
	url = "?" + curvar + models + outputDate;
	sendURL(url);
    };

// CREATE URL WHEN MODELS-APPLY IS CLICKED
function handleWASApply () {
	const checked = document.getElementById('was-dropdown');
	var text = checked.querySelector('input[type="radio"]:checked').parentElement.innerText;
	text = text.split(' ').join('_').toLowerCase();
	url = "?tab=forecast&section=was&country=" + text;
	sendURL(url);
    };	

// CREATE A DICTIONARY OF IDs TO CREATE URL OUTPUTS
const urlOuputDict = {
    "#group-1-toggle": "?tab=forecast&section=models",
    "#group-2-toggle": "?tab=forecast&section=prob",
    "#group-3-toggle": "?tab=forecast&section=was",
    "#forecast-tab": "?tab=forecast",
    "#evaluation-tab": "?tab=evaluation",
    "#observations-tab": "?tab=observations",
    "#nrt-evaluation": "?tab=evaluation&section=visual_comparison",
    "#scores-evaluation": "?tab=evaluation&section=statistics",
    "#rgb": "?tab=observations&section=eumetsat-rgb",
    "#visibility": "?tab=observations&section=visibility", 
    "#models-apply": handleModelsApply,
    "#was-apply": handleWASApply,
};

$(document).ready(function () {
    // Match ID with the tooglemap key and output url value
    $(document).on('click', Object.keys(urlOuputDict).join(', '), function () {
	var selector = "#" + $(this).attr('id');
	var value = urlOuputDict[selector];
	var url = typeof value === 'function' ? value() : value;
	sendURL(url);
    });
});
