// ======================================================================
//
// 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 = false;

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(" ");
        var iElements = document.getElementsByClassName('idp').length;

        var iShown=0;
        // reduce boxes based on filter using AND condition
        for (var i = 0; i < iElements; 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';
            iShown += bShow ? 1 : 0;
        }

        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';
        }

        var sCounter=(iShown<iElements)
            ? (
                iShown==0
                    ? t('filter-none')
                    : t('filter-visible') + ': <strong>' + iShown+'</strong> / '+iElements
            )
            : t('filter-total') +': <strong>'+ iElements + '</strong>';
        
        document.getElementById('filterCounter').innerHTML = sCounter;
        document.getElementById('resetfilter').style.visibility = (q > '' ? '' : 'hidden');
        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() {
    displayClass('showForLogin', true);
    if (oFilter) {
        var q = localStorage.getItem(sLsvar);
        if (!q) {
            q = '';
        }

        // oFilter.innerHTML = ''
        //     // + t('filter-idps-label') + '<br>'MAXRECORDS
        //     + '<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>'
        //     + '<span id="filterCounter"></span>'
        //     +'<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';
}


/**
 * Show or hide a group of objects by given class name
 * @param {string} sClass2Show  Classname to show or hide
 * @param {string} $bShow       true= show; false = hide
 */
function displayClass(sClass, bShow){
    aObjects = document.getElementsByClassName(sClass);
    for (var i = 0; i < aObjects.length; i++) {
        aObjects[i].style.display = (bShow ? 'block' : 'none');
    }
}

/**
 * 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";
    try {
        const response = await fetch(url);
        if (!response.ok) {

            // No Shibboleth ... no response or 404 or other error
            showError(
                t('shib-check-failed') + " " + response.status + '<br>' 
                + t('shib-hide-login')
            );
            if(bShowLoginOnError) {
                showFilterBox();
            } else {
                displayClass('showForLogin', false);
            }
            throw new Error(`Response status: ${response.status}`);
        }

        // Shibboleth found - check if logged in
        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");
            displayClass('showIfLoggedIn', true);
            if(!bShowLoginOnError) {
                displayClass('showForLogin', false);
            }
        }
    } catch (error) {
        console.error(error.message);
    }
}

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

/**
 * Init step 1: load language file and make it available in aLang
 */
async function init(){
    fetch('lang/' + sLang + '.json')
    .then(response => response.json())
    .then(aLang => {
        initStep2(aLang)
    })
    .catch(error => console.log(error))
    ;

}

/**
 * Init step 2: Check Shibboleth session
 */
async function initStep2(langArray) {
    aLang = langArray;
    checkSession();
}


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

// MAIN
init();

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