﻿/**
 * identification.js
 */
Identification = {
    external: {
        viewModel: new Object(),
        setCode(value) {
            // Si on a un code dans external.oldCode, on le met dans l'obs
            // Puis on trigger l'event pour le libellé puis on focus le pass
            Identification.obs.forms.set("code", value);
            $("#code").trigger("input");
            $("#pass").focus();
        }
    },
    obs: kendo.observable({
        // Les loadings, global et intra-partial
        loadings: {
            global: true,
            inner: false
        },

        // Divers
        misc: {
            hideSecurityCheck: true,
        },

        // Data récupérées des formulaires par data-bind
        forms: {
            code: null,
            pass: null,
            email: null,

            identifiantReset: null,

            newpass: null,
            newpassConfirm: null,
            passwordSafe: false,
            shouldBeEnabled() {
                const passwordSafe = Identification.obs.forms.get("passwordSafe");
                return passwordSafe == true;
            }
        },

        // Ces fonctions sont bind dans le DOM par kendo.
        load: {
            identification() { Identification.Routing.goto("IDENTIFICATION"); },
            forgotPassword() { Identification.Routing.goto("FORGOT_PASSWORD"); },
            openMobile(e) { Identification.Routing.goto("OPEN_MOBILE", e); },
            openMicrosoftAuth() { Identification.Routing.goto("OPEN_MICROSOFT_AUTH"); },
            openGoogleAuth() { Identification.Routing.goto("OPEN_GOOGLE_AUTH"); },
            openHelp() { Identification.Routing.goto("OPEN_HELP"); },
        },

        // Ces fonctions sont également bind dans le DOM
        connect: {
            motDePasse(e) { Identification.MotDePasse.connect(e); }
        },

        // Autres actions, comme réinitialisation, otp, je sais pas
        actions: {
            changePassword(e) { Identification.MotDePasse.change(e); },
            resetPassword(e) { Identification.MotDePasse.reset(e); },
            linkAccount(e) { Identification.LiaisonSociale.linkAccount(e) },
            sendLinkageEmail(e) { Identification.LiaisonSociale.sendLinkageEmail(e) },
        }
    }),
    Routing: null,
    init: () => {
        // On instancie notre classe de routing.
        Identification.Routing = new IdentificationRouting();

        // Binding + dissimulation du loading.
        kendo.bind($("body"), Identification.obs);
        Identification.utils.loadings.global.hide();

        // On récup la VuePartielle active du viewModel, et si
        // il y a un afterLoad, on l'execute.
        const currentView = Identification.external.viewModel.VuePartielle;
        Identification.Routing.currentView = currentView;
        Identification.Routing.executeAfterLoad(currentView);

        // Snackbar, ça init on met le binding
        Identification.snackbar.init();
    },
    snackbar: {
        get() { return $("#login-notification"); },
        hide() { Identification.snackbar.get().css("opacity", "0"); },
        show() { Identification.snackbar.get().css("opacity", "1"); },
        reposition() {
            const snackbar = Identification.snackbar.get();
            const snackbarHeight = snackbar.outerHeight();
            const snackbarWidth = snackbar.outerWidth();

            const viewPortWidth = $(window).outerWidth();
            const loginOffsets = $("#login").offset();

            const adjustedTop = loginOffsets.top / 2 - snackbarHeight / 2;
            const adjustedWidth = viewPortWidth / 2 - snackbarWidth / 2;
            snackbar.css({ left: adjustedWidth, top: adjustedTop });
        },
        init() {
            Identification.snackbar.get().on("click", () => Identification.snackbar.hide());            

            $(window).resize(() => {
                if (Identification.snackbar.get().length)
                    Identification.snackbar.reposition();
            });
        },
        set(str) {
            Identification.snackbar.get().find(".login-notification-snack-message").html(str);
            Identification.snackbar.show(); 
            $(window).trigger("resize");
        }
    },
    utils: {
        loadings: {
            global: {
                hide() { Identification.obs.set("loadings.global", false); },
                show() { Identification.obs.set("loadings.global", true); },
            },
            inner: {
                hide() { Identification.obs.set("loadings.inner", false); },
                show() { Identification.obs.set("loadings.inner", true); }
            }
        },
        rebindPartial() {
            kendo.unbind($("body"));
            kendo.bind($("body"), Identification.obs);
        },
        clearForm() {
            try {
                for (const item in Identification.obs.forms.toJSON())
                    if (!!Identification.obs.forms.get(item))
                        Identification.obs.forms.set(item, null);
            } catch { }
        },
        togglePassword(element) {
            const ua = window.navigator.userAgent;
            const trident = ua.indexOf('Trident/');
            const edge = ua.indexOf('Edge/');
            const edgeChromium = ua.indexOf("Edg/");

            if (trident > 0 || edge > 0 || edgeChromium > 0) {
                $(element).hide();
            }
            else {
                $(element)
                    .off('click.identification')
                    .on('click.identification', function (e) {
                        const clickedInput = $(e.currentTarget).siblings('input');
                        const clickedEye = $(e.currentTarget);
                        const currentStateInput = clickedInput.attr('type');
                        const currentStateEye = clickedEye.attr('class');

                        (currentStateEye.indexOf('fa-eye-slash') > 0)
                            ? clickedEye.addClass('fa-eye').removeClass('fa-eye-slash')
                            : clickedEye.addClass('fa-eye-slash').removeClass('fa-eye');

                        clickedInput.attr('type', (currentStateInput === 'password') ? 'text' : 'password');
                    });
            }
        },
        placeholder: {
            setHeight() {
                const selector = $("#partial-placeholder");

                // Obligé de setTimeout, j'ai honte mais c'est pour éviter le clignotement
                // lors du changement de vue.
                Identification.utils.placeholder.clearHeight();

                setTimeout(() => {
                    const height = selector.outerHeight(true);
                    selector.css("height", height);
                }, 500);
            },
            clearHeight() {
                $("#partial-placeholder").css("height", "");
            }
        },
        inputs: {
            caseAdjust(ctx) {
                const selector = $(ctx);
                const value = selector.val();

                if (!!value) selector.css('text-transform', (value.indexOf('@') > -1) ? 'lowercase' : 'uppercase');
            },
            bindings: {
                set() {
                    $('#login')
                        .off("input.identificationplaceholder")
                        .on("input.identificationplaceholder", ".partial-body input", (e) => {
                            const senderLength = $(e.target).val()?.length;
                            const libelleInput = $(e.target).closest('div[class^=identification-input-group')?.find('span');

                            libelleInput.css('opacity', ((senderLength === 0 && typeof senderLength !== "undefined") ? 0 : 1));
                        });

                    $('#login')
                        .off("blur.identificationplaceholder")
                        .on("blur.identificationplaceholder", ".partial-body input[name='code']",
                            (e) => Identification.utils.inputs.caseAdjust(e.target)
                        );
                }
            }
        }
    }
}

// Point d'entrée
$(document).ready(() => {
    Identification.init();
    
    // Est-ce qu'on a des erreurs provenant du back ? Si oui on toast la snackbar
    const message = Identification.external.viewModel.Message;
    if (!!message) Identification.snackbar.set(message);
});

// On set la height quand la page a fini de load,
// important que ça soit dans le on("load") et pas le on ready.
$(window).on("load", () => {
    Identification.utils.placeholder.setHeight();
});