class ExportPopup extends HTMLElement{

    constructor(exportCallback){
        super();
        this.exportCallback = exportCallback;
    }

    updateValuesOnOpen(blocks, startDateTimeMs, endDateTimeMs){

        this.setDateTimeInputs(startDateTimeMs, "start");
        this.setDateTimeInputs(endDateTimeMs, "end");

        let defaultBinningValue = Math.ceil(((endDateTimeMs - startDateTimeMs)/1000)/1000);
        let binningInput = this.getElementsByClassName("binning-input")[0];
        binningInput.value = defaultBinningValue;

        this.getElementsByClassName("export-select-all-checkbox")[0].checked = false;

        let exportCurvesContainer = this.getElementsByClassName("export-curves-container")[0]
        exportCurvesContainer.innerHTML = ""
        for (let block of blocks){
            for(let curve of block["curves"]){
                let exportCurveContainer = document.createElement("div");
                exportCurveContainer.classList.add("export-curve-container");
                let exportCheckboxCurve = document.createElement("input");
                exportCheckboxCurve.type = "checkbox"
                exportCheckboxCurve.value = curve["name"]
                let exportCurveLabel = document.createElement("span");
                exportCurveLabel.innerHTML = curve["label"]
                exportCurveContainer.appendChild(exportCheckboxCurve);
                exportCurveContainer.appendChild(exportCurveLabel);
                exportCurvesContainer.appendChild(exportCurveContainer);
            }
        }
    }

    toggleAllCurves(){
        let exportCurvesContainer = this.getElementsByClassName("export-curves-container")[0];
        let checked = this.getElementsByClassName("export-select-all-checkbox")[0].checked;
        for(let node of exportCurvesContainer.childNodes){
            node.getElementsByTagName("input")[0].checked = checked;
        }
    }

    setDateTimeInputs(timestamp, type){
        let date = new Date(timestamp)
        this.getElementsByClassName(`export-${type}-hour`)[0].value = date.getHours();
        this.getElementsByClassName(`export-${type}-minute`)[0].value = date.getMinutes();

        let exportTypeDate = this.getElementsByClassName(`export-${type}-date`)[0];
        exportTypeDate.valueAsDate = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate())) // date input uses UTC

    }

    getDateTimeTimestampMsInput(type){
        let dateInputValue = this.getElementsByClassName(`export-${type}-date`)[0].valueAsDate;
        dateInputValue.setHours(0,0,0,0);

        let hours = this.getElementsByClassName(`export-${type}-hour`)[0].value;
        if(hours < 0 || hours > 23){
            alertify.error("Invalid hours");
            throw RangeError;
        }
        let minutes = this.getElementsByClassName(`export-${type}-minute`)[0].value;
        if(minutes < 0 || minutes > 59){            
            alertify.error("Invalid minutes");
            throw RangeError;
        }
        return dateInputValue.getTime() + hours*60*60*1000 + minutes*60*1000;
    }

    getSelectedVariables(){
        let selectedVariables = []
        let exportCurvesContainer = this.getElementsByClassName("export-curves-container")[0];

        for(let node of exportCurvesContainer.childNodes){
            let input = node.getElementsByTagName("input")[0]
            if(input.checked){
                selectedVariables.push(input.value)
            }
        }
        return selectedVariables;
    }


    doExportCallback(){
        let startDateTimeMs = null, endDateTimeMs = null;
        try{
            startDateTimeMs = this.getDateTimeTimestampMsInput("start");
        }
        catch(e){
            return
        }

        try{
            endDateTimeMs = this.getDateTimeTimestampMsInput("end");
        }
        catch(e){
            return
        }

        if (endDateTimeMs <= startDateTimeMs){
            alertify.error("End date is below or equal to start date.");
            return
        }

        let nanRepresentation = this.getElementsByClassName("nan-input")[0].value; 

        let binningCheckbox = this.getElementsByClassName("binning-checkbox")[0];
        let binningValue = null;
        if(binningCheckbox.checked){
            let binningInput = this.getElementsByClassName("binning-input")[0];
            binningValue = binningInput.value;
            if (binningValue <= 0){
                alertify.error("Binning is negative or 0");
                return
            }
        }

        let selectedVariables = this.getSelectedVariables();

        if(selectedVariables.length == 0){
            alertify.error("No curves selected");
        }
        else
        {   
            this.hide();
            this.exportCallback(selectedVariables, startDateTimeMs, endDateTimeMs, nanRepresentation, binningValue);
        }
    }

    hide(){
        this.style.visibility = "hidden";
        window.removeEventListener("click", this.backgroundClickCallback);
    }

    backgroundClickCallback = ({target}) => {
        if(target.id == "export-popup"){
            this.hide();
        }
    }

    show(variables, startTime, endTime){
        this.style.visibility = "visible";
        this.updateValuesOnOpen(variables, startTime, endTime);
        window.addEventListener("click", this.backgroundClickCallback);
    }

    connectedCallback(){
        this.render();
        this.hide();    
        this.getElementsByTagName("img")[0].onclick = () => {this.hide();};
        this.getElementsByClassName("export-select-all-checkbox")[0].onclick = () => {this.toggleAllCurves();};
        this.getElementsByClassName("export-button")[0].onclick = () => {this.doExportCallback();};

    }

    render(){
        this.innerHTML = `
        <link rel="stylesheet" href="components/export_popup/export_popup.css"/>
        <div id="export-popup">
            <div id="export-popup-container">
                
                <div id="export-popup-header">
                    <span>Export</span>
                    <img src="res/close.png"/>
                </div>

                <div id="export-popup-content">
                    <div class="export-section-container" id="export-times-section">
                        <div class="time-container">
                            <span class="time-label">Start : </span>
                            <input type=date class="export-start-date">
                            <input type=number class="export-start-hour" min="00" max="23">
                            <input type=number class="export-start-minute" min="00" max="59">
                        </div>

                        <div class="time-container">
                            <span class="time-label">End : </span>
                            <input type=date class="export-end-date">
                            <input type=number class="export-end-hour" min="00" max="23">
                            <input type=number class="export-end-minute" min="00" max="59">
                        </div>
                        
                        <div>
                            <span>NaN value : </span>
                            <input type=text class="nan-input" value="" spellcheck=false>
                        </div>

                        <div class="binning-container">
                            <input type=checkbox class="binning-checkbox">
                            <span class="binning-label">Binning (s) : </span>
                            <input type=number class="binning-input" min=1>
                        </div>
                    </div>

                    <div id="export-button-container">
                        <button class="export-button">Export</button>
                    </div>
                    
                    <div class="export-section-container" id="export-curves-section">

                        <span>Curves to export</span>
                        <div>
                            <input type=checkbox class="export-select-all-checkbox">
                            <span>Select all curves</span>
                        </div>
                        <div class="export-curves-container">

                        </div>
                        
                    </div>

                </div>

            </div>
        </div>
        `;
    }
}

customElements.define("sea-export-popup", ExportPopup);