//var DEBUG = true;
//if (!DEBUG) {
//    _consoleLog = console.log;
//    console.log = () => { };
//}

window.CurrentlyWorkingFunctions = 0;
window.LoadingMachines = [];
window.UpdateSessionStateIntervals = [];
async function doThenReloadAsync(whatToDoAsync, args) {
    var FuncResult = await whatToDoAsync.apply(this, args);
    //if (FuncResult.AfterReloadFunc !== undefined) {
    //    sessionStorage.setItem("reloadFunc", FuncResult.AfterReloadFunc.toString());
    //}
    safeReload();
}
function doThenReload(whatToDo, args) {
    whatToDo.apply(this, args)
    safeReload();
}
function safeReload() {
    setInterval(() => {
        console.log('Checking if I can reload.');
        if (window.CurrentlyWorkingFunctions > 0) {
            console.log('Cant reload. CurrentlyWorkingFunctions: ' + window.CurrentlyWorkingFunctions);
            return;
        }
        else {
            location.reload();
        }
    }, 1000);
}
function delayedReload(delay = 5000) {
    setTimeout(() => location.reload(), delay);
}
function timerCountDown(time, counterElementId) {
    var timeLeft = time - 1;
    var textHolder = document.getElementById(counterElementId);
    var countdownInterval = setInterval(() => {
        if (timeLeft <= 0) {
            clearInterval(countdownInterval);
            if (typeof cleanupFunction === "function") { cleanupFunction(textHolder); }
        }
        if (textHolder === null || typeof textHolder === 'undefined') {
            clearInterval(countdownInterval);
            return;
        }
        textHolder.innerHTML = 'Sesión en curso. Tiempo restante: ' + new Date(timeLeft * 1000).toISOString().substr(11, 8);
        timeLeft -= 1;
    }, 1000);
}
function lifeSpan(token) {
    console.log('Getting lifespan for: ' + token);
    return $.ajax({
        url: 'https://cabinas.sintia.com.ar/coordinador/api/Session/LifeSpan?Token=' + token,
        type: 'GET',
        error: (err) => handleError(err)
    });
}
function updateSessionState(token, machineId, userId, currentlyActive) {
    if (window.LoadingMachines.includes(machineId)) {
        return;
    } 
    $.ajax({
        url: 'GetSessionModel',
        type: 'POST',
        data: JSON.stringify({ "Token": token, "MachineId": machineId, "UserId": userId, "CurrentState": currentlyActive }),
        contentType: 'application/json; charset=utf-8',
        error: function (err) { console.log('Error: ' + err.statusText); },
        success: function (result) {
            if (result === 'Ok') {
                window.UpdateSessionStateIntervals = window.UpdateSessionStateIntervals.filter(x => x.machineId !== machineId);
                return;
            }
            document.getElementById('tr_' + machineId).innerHTML = result.ViewHtml;
            if (result.SessionTimeLeft !== 0) {
                timerCountDown(result.SessionTimeLeft, 'countdown_' + machineId);
            }
        },
        async: true
    });
}
function resetSession(token, userId, machineId) {
    setAttributeMultiple(['btnEndSession_' + machineId, 'btnResetSession_' + machineId, 'btnIngresar_' + machineId, 'btnCopyLink_' + machineId], 'disabled', '');
    window.CurrentlyWorkingFunctions++;
    window.LoadingMachines.push(machineId);
    $.ajax({
        url: 'Resetear',
        type: 'POST',
        data: JSON.stringify({ "Token": token }),
        contentType: 'application/json; charset=utf-8',
        error: function (err) { console.log('Error: ' + err.statusText); },
        success: function (result) {
            console.log(result);
            window.CurrentlyWorkingFunctions--;
            window.LoadingMachines = window.LoadingMachines.filter(item => item !== machineId);
            updateSessionState(token, machineId, userId, false);
        },
        async: true
    })
}
function endSession(token, userId, machineId) {
    setAttributeMultiple(['btnEndSession_' + machineId, 'btnResetSession_' + machineId, 'btnIngresar_' + machineId, 'btnCopyLink_' + machineId], 'disabled', '');
    document.getElementById('Loader_' + machineId).style.opacity = 1;
    window.LoadingMachines.push(machineId);
    window.CurrentlyWorkingFunctions++;
    $.ajax({
        url: 'Terminar',
        type: 'POST',
        data: JSON.stringify({ "Token": token }),
        contentType: 'application/json; charset=utf-8',
        error: function (err) { console.log('Error: ' + err.statusText); },
        success: function (result) {
            console.log(result);
            document.getElementById('Loader_' + machineId).style.opacity = 0;
            window.LoadingMachines = window.LoadingMachines.filter(item => item !== machineId);
            window.CurrentlyWorkingFunctions--;
            updateSessionState(token, machineId, userId, true);
        },
        async: true
    })
}
function setAttributeMultiple(controls, attributeName, attributeValue) {
    if (controls === undefined || !controls.constructor === Array)
        return;
    try {
        controls.forEach(x => document.getElementById(x).setAttribute(attributeName, attributeValue));
    } catch (e) {
        console.log('Button disabling error: ' + e);
    }
}
function removeAttributeMultiple(controls, attributeName) {
    if (controls === undefined || !controls.constructor === Array)
        return;
    try {
        controls.forEach(x => document.getElementById(x).removeAttribute(attributeName, ''));
    } catch (e) {
        console.log('Button enabling error: ' + e);
    }
}
async function LoadingVmOnLoad(accessDelayMilliseconds, url, token) {
    var totalDelay = accessDelayMilliseconds;
    console.log('Delay:' + totalDelay);
    var loadingTitle = document.getElementById('loading-title');
    setTimeout(() => loadingTitle.innerText = "Comprobando enlace...", totalDelay / 3);
    setTimeout(() => loadingTitle.innerText = "Estableciendo conexión...", (totalDelay / 3) * 2);
    let newWindowWasBlocked = !await waitThenGoToVirtual(url, null, null, token);
    document.getElementById('goInManually').style.opacity = 1;
    document.getElementById('loadingVm').style.opacity = 0;
    loadingTitle.innerText = 'Conexión establecida.';
}
//Tries to go to a new window. Returns true if it wasn't blocked; else false.
async function goToVirtualNewWindow(url) {
    console.log('Going to: ' + url);
    var newWin = window.open(url, '_blank', 'width=' + ((window.screen.availWidth / 100) * 90) + ', height=' + (window.screen.availHeight / 100) * 91);
    if (!newWin || newWin.closed || typeof newWin.closed == 'undefined') {
        alert('El navegador bloqueó la ventana emergente. Por favor habilite los pop-ups o intente copiar el enlace e ingresar manualmente.');
        return { Result: false };
    }
    newWin.focus();
    return true;
}
function goToVirtual(machineId, userId, sessionDurationId) {
    console.log("Machine: " + machineId);
    console.log("User: " + userId);
    getLink(machineId, userId, sessionDurationId, (result) => { window.CurrentlyWorkingFunctions--; waitThenGoToVirtual(result.Url, machineId, userId, result.Token, 5, 2000, result.AccessDelay); });
}
function getVirtualLink(machineId, userId, sessionDurationId, machineName) {
    console.log("Machine: " + machineId);
    console.log("User: " + userId);
    getLink(machineId, userId, sessionDurationId, (result) => { waitThenCopyLink(result.Url, result.Token, userId, 5, 2000, result.AccessDelay, machineName, machineId) });
}
var originalUnload = window.onbeforeunload;
function activateReloadWarning() {
    window.onbeforeunload = function () {
        return "Se recomienda esperar la carga antes de recargar el sitio.";
    }
}
function deactivateReloadWarning() {
    window.onbeforeunload = originalUnload;
}
function getLink(machineId, userId, sessionDurationId, successFunction) {
    setAttributeMultiple(['btnIngresar_' + machineId, 'btnCopyLink_' + machineId, 'sessionDuration_' + machineId], 'disabled', '');
    activateReloadWarning();
    console.log("Machine: " + machineId);
    console.log("User: " + userId);
    window.LoadingMachines.push(machineId);
    var sessionDuration = document.getElementById(sessionDurationId).value;
    console.log("SessionDuration: " + sessionDuration);
    document.getElementById('Loader_' + machineId).style.opacity = 1;
    states(machineId);
    window.CurrentlyWorkingFunctions++;
    $.ajax({
        url: 'Compartir',
        type: 'POST',
        data: JSON.stringify({ "MachineId": machineId, "UserId": userId, "SessionDuration": sessionDuration }),
        contentType: 'application/json; charset=utf-8',
        error: function (err) { console.log('Error: ' + err.statusText); },
        success: function (result) {
            deactivateReloadWarning();
            console.log('Compartir result: ' + result);
            successFunction(result);
        },
        async: true
    });

}
function handleError(err) {
    console.log('Error: ' + err.statusText);
}
async function waitThenGoToVirtual(url, machineId, userId, token, readyErrorTolerance = 3, sleepPerIteration = 2000, accessDelaySeconds = 60) {
    console.log('sleepPerIteration: ' + sleepPerIteration);
    console.log('accessDelay: ' + accessDelaySeconds);
    console.log('url: ' + url);
    console.log('token: ' + token);
    let MaxSleep = accessDelaySeconds * 1000;
    let IsReady = false;
    console.log('IsReady: ' + IsReady);
    console.log('readyErrorTolerance: ' + readyErrorTolerance);
    console.log('MaxSleep: ' + MaxSleep);
    while (!IsReady && readyErrorTolerance > 0 && MaxSleep > 0) {
        console.log('Pulling API to navigate');
        console.log('IsReady: ' + IsReady);
        console.log('readyErrorTolerance: ' + readyErrorTolerance);
        console.log('MaxSleep: ' + MaxSleep);
        var Response = await ready(token);
        console.log('Response from ready: ' + Response);
        switch (Response) {
            case undefined: readyErrorTolerance--; continue;
            case null: readyErrorTolerance--; continue;
            case 'False': await sleep(sleepPerIteration); MaxSleep -= sleepPerIteration; continue;
            case 'True': IsReady = true; break;
        }
    }
    if (machineId === null || userId === null || typeof machineId === 'undefined' || typeof userId === 'undefined')
        return await goToVirtualNewWindow(url);
    window.LoadingMachines = window.LoadingMachines.filter(item => item !== machineId);
    updateSessionState(token, machineId, userId, false);
    return await goToVirtualNewWindow(url);
}
async function waitThenCopyLink(url, token, userId, readyErrorTolerance = 3, sleepPerIteration = 2000, accessDelaySeconds = 60, machineName, machineId) {
    console.log('Copying: ' + url);
    let MaxSleep = accessDelaySeconds * 1000;
    let IsReady = false;
    while (!IsReady && readyErrorTolerance > 0 && MaxSleep > 0) {
        console.log('Pulling API to Copy');
        console.log('IsReady: ' + IsReady);
        console.log('readyErrorTolerance: ' + readyErrorTolerance);
        console.log('MaxSleep: ' + MaxSleep);
        var Response = await ready(token);
        console.log('Response from ready: ' + Response);
        switch (Response) {
            case undefined: readyErrorTolerance--; continue;
            case null: readyErrorTolerance--; continue;
            case 'False': await sleep(sleepPerIteration); MaxSleep -= sleepPerIteration; continue;
            case 'True': IsReady = true; break;
        }
    }
    window.CurrentlyWorkingFunctions--;
    copyToClipboard(url, 'Se copió la URL de ' + machineName + ' al portapapeles.');
    document.getElementById('Loader_' + machineId).style.opacity = 0;
    endStates(machineId);
    window.LoadingMachines = window.LoadingMachines.filter(item => item !== machineId);
    updateSessionState(token, machineId, userId, false);
}
function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}
function ready(token) {
    console.log('Checking ready for: ' + token);
    return $.ajax({
        url: 'https://cabinas.sintia.com.ar/coordinador/api/Session/Ready?Token=' + token,
        type: 'GET',
        error: (err) => handleError(err)
    });
}
function endStates(machineId) {
    var statesDiv = document.getElementById('States_' + machineId);
    statesDiv.style.opacity = 0;
    statesDiv.innerText = "";
}
function states(machineId, expectedDelay) {
    var statesDiv = document.getElementById('States_' + machineId);
    statesDiv.style.opacity = 1;
    var Message = "Obteniendo URL, puede tardar " + (expectedDelay || "varios minutos.");
    statesDiv.innerText = Message;
    setTimeout(() => { statesDiv.innerText = "Comprobando enlace..."; }, 25000);
    setTimeout(() => { statesDiv.innerText = "Estableciendo conexión..."; }, 40000);
}
function copyToClipboard(text, alertText) {
    if (document.hasFocus()) {
        navigator.clipboard.writeText(text);
        alert(alertText || 'Se copió la URL al portapapeles.');
        return;
    }
    $(window).focus(() => {
        navigator.clipboard.writeText(text);
        $(window).unbind('focus');
        alert(alertText || 'Se copió la URL al portapapeles.');
    });
}