// ======================================================================
//
// AAI LOGIN WITH SHIBBOLETH HANDLING MULTIPLE ORGANIZATIONS
// 
// javascript functions for mode = "boxes"
//
// License: GNU GPL 3.0
// Source: https://git-repo.iml.unibe.ch/iml-open-source/login-aai
// ======================================================================


// ----------------------------------------------------------------------
// VARS
// ----------------------------------------------------------------------

// for development without local shibboleth - set to true
var bShowLoginOnError = true;

var oFilter = document.getElementById('filterbox');
var sLang =   document.getElementById('lang').value;
var aLang={};
var sLsvar = 'aailogin-q';

// ----------------------------------------------------------------------
// FUNCTIONS
// ----------------------------------------------------------------------

/**
 * Apply filter and reduce listed Idps
 */
function applyfilter() {

    if (oFilter) {
        var q = document.getElementById('filter').value;
        var aQ = q.split(" ");

        // reduce boxes based on filter using AND condition
        for (var i = 0; i < document.getElementsByClassName('idp').length; i++) {
            var idp = document.getElementsByClassName('idp')[i];

            var bShow = true;
            if (q != "") {
                var sText = idp.innerHTML.replace(/<[^>]*>/g, "");
                for (var iPart = 0; iPart < aQ.length; iPart++) {
                    var qPart = aQ[iPart];
                    bShow = bShow & sText.toLowerCase().indexOf(qPart.toLowerCase()) >= 0;

                }
            }
            idp.className = bShow ? 'idp' : 'idp hide';
            document.getElementById('resetfilter').style.display = (q > "") ? 'inline' : 'none';
        }

        var aBtns = document.getElementsByClassName('filterbutton');
        for (var i = 0; i < aBtns.length; i++) {
            var bMarked = false;
            for (var iPart = 0; iPart < aQ.length; iPart++) {
                var qPart = aQ[iPart];
                var id2search = 'filterbtn-dot-' + qPart.replace(/^./, '');
                var qPart = aQ[iPart];
                if (aBtns[i].id == id2search) {
                    bMarked = true;
                    break;
                }
            }
            aBtns[i].className = bMarked ? 'filterbutton active' : 'filterbutton';
        }

        document.getElementById('filter').focus();
        localStorage.setItem(sLsvar, q);
    };
}

/**
 * Set a new filter value or reset it
 * @param {string} sNewFiltervalue New value to write into the filter field
 */
function setFilter(sNewFiltervalue) {
    document.getElementById('filter').value = sNewFiltervalue;
    applyfilter();
}

/**
 * Reset the filter and show all Items
 */
function resetFilter() {
    setFilter("");
}
/**
 * Enable filter box if static_link is in use
 * It renders an input field, reads the last search value from local storage 
 * and apllies this filter
 */
function showFilterBox() {
    if (oFilter) {
        var q = localStorage.getItem(sLsvar);
        if (!q) {
            q = '';
        }

        oFilter.style.display = 'block';

        oFilter.innerHTML = ''
            // + t('filter-idps-label') + '<br>'
            + '<input type="text" id="filter" placeholder="'+t('filter-idps-placeholder')+'" onchange="applyfilter()" onkeydown="applyfilter()" onkeyup="applyfilter()" value=""/>'
            + '<a href="#" id="resetfilter" onclick="resetFilter(); return false;" title="'+t('resetfilter-title')+'"> X </a><br>'
            ;
        setFilter(q);

        for (var i = 0; i < document.getElementsByClassName('idp').length; i++) {
            var idp = document.getElementsByClassName('idp')[i];
            idp.setAttribute("onclick", "localStorage.setItem(sLsvar,this.innerText);");
        }
    };
};

// ----------------------------------------------------------------------

/**
 * Get translated text by a given keyword
 * @param {string} sKeyword key of the translation text
 * @returns 
 */
function t(sKeyword) {
    if (aLang[sKeyword]) {
        return aLang[sKeyword];
    } else {
        return "MISS: [" + sKeyword + "] in [" + sLang + '.json]';
    }
}

// ----------------------------------------------------------------------

/**
 * Show error message
 * @param {string} $sMessage message text
 */
function showError($sMessage){
    document.getElementById('errorbox').innerHTML = $sMessage;
    document.getElementById('errorbox').style.display = 'block';
}

/**
 * Check if user is logged in in shibboleth
 * It shows an error, ib shibboleth is not available.
 * It detects if a user is logged in.
 */
async function checkSession() {
    const url = "/Shibboleth.sso/Session";
    if(!bShowLoginOnError) {
        document.getElementById('shib-select-idp').style.display = 'none';
    }
    try {
        const response = await fetch(url);
        if (!response.ok) {
            showError(
                t('shib-check-failed') + " " + response.status + '<br>' 
                + t('shib-hide-login')
            );
            if(bShowLoginOnError) {
                showFilterBox();
            }
            throw new Error(`Response status: ${response.status}`);
        }

        const body = await response.text();
        if (body.indexOf("was not found") > 0) {
            // console.log("Not logged in");
            // We show the login to idp selection
            showFilterBox();
        } else {
            // console.log("Logged in already");
            document.getElementById('sshib-check-logged-in').style.display = 'block';
        }

        // ...
    } catch (error) {
        console.error(error.message);
    }
}



async function init(){
    fetch('lang/' + sLang + '.json')
    .then(response => response.json())
    .then(aLang => {
        initStep2(aLang)
    })
    .catch(error => console.log(error))
    ;

}

async function initStep2(langArray) {
    aLang = langArray;
    checkSession();
}

// ----------------------------------------------------------------------
// INIT
// ----------------------------------------------------------------------

init();

// ----------------------------------------------------------------------