/**
 * Master Login
 *
 * @module package/quiqqer/masterlogin/bin/js/frontend/controls/MasterLogin
 * @author www.pcsg.de (Patrick Müller)
 */
define('package/quiqqer/masterlogin/bin/js/frontend/controls/MasterLogin', [

    'qui/QUI',
    'qui/controls/Control',
    'qui/controls/windows/SimpleConfirmWindow',

    'package/quiqqer/masterlogin/bin/js/frontend/Manager',
    'package/quiqqer/masterlogin/bin/js/frontend/controls/UserSelectPopup',

    'Locale',
    'Ajax',
    'Mustache',
    URL_OPT_DIR + 'bin/quiqqer-asset/animejs/animejs/lib/anime.min.js',

    'text!package/quiqqer/masterlogin/bin/js/frontend/controls/MasterLogin.html',
    'css!package/quiqqer/masterlogin/bin/js/frontend/controls/MasterLogin.css'

], function (QUI, QUIControl, QUISimpleConfirmWindow, MasterLoginManager, UserSelectPopup, QUILocale, QUIAjax, Mustache, animejs,
             template
) {
    'use strict';

    var lg = 'quiqqer/masterlogin';

    return new Class({

        Extends: QUIControl,
        Type: 'package/quiqqer/masterlogin/bin/js/frontend/controls/MasterLogin',

        Binds: [
            '$onInject',
            '$toggleVisibility',
            '$openUserSelect',
            '$openLogBackConfirm',
            '$showContainer',
            '$hideContainer',
            '$showOpenBtn',
            '$hideOpenBtn'
        ],

        options: {
            slave: false,      // set to true if user is logged in as slave (shows logback option and warning)
            masteruser: '',         // Info Text about master user
            slaveuser: '',         // Info Text about slave user
            csrftoken: ''
        },

        initialize: function (options) {
            this.parent(options);

            this.$visible = false;
            this.$Content = null;
            this.$animationRunning = false;

            this.addEvents({
                onInject: this.$onInject
            });
        },

        /**
         * Event: onInject
         */
        $onInject: function () {
            MasterLoginManager.setCsrfToken(this.getAttribute('csrftoken'));
            this.MasterUser = JSON.parse(this.getAttribute('masteruserdata'));
            this.SlaveUser = JSON.parse(this.getAttribute('slaveuserdata'));

            const userDdata = {
                id: this.MasterUser.id,
                name: this.MasterUser.name,
                email: this.MasterUser.email
            };

            let title = QUILocale.get(lg, 'controls.MasterLogin.info.admin');

            if (this.getAttribute('slave')) {
                userDdata.id = this.SlaveUser.id;
                userDdata.name = this.SlaveUser.name;
                userDdata.email = this.SlaveUser.email;
                userDdata.company = this.SlaveUser.company;

                title = QUILocale.get(lg, 'controls.MasterLogin.info.slave');
            }

            this.$Content = new Element('div', {
                'class': 'quiqqer-masterlogin',
                html: Mustache.render(template, {
                    slave: this.getAttribute('slave') ? true : false,
                    title: title,
                    id: userDdata.id,
                    name: userDdata.name,
                    email: userDdata.email,
                    company: userDdata.company,
                    idLabel: QUILocale.get(lg, 'controls.MasterLogin.tpl.label.id'),
                    nameLabel: QUILocale.get(lg, 'controls.MasterLogin.tpl.label.name'),
                    emailLabel: QUILocale.get(lg, 'controls.MasterLogin.tpl.label.email'),
                    companyLabel: QUILocale.get(lg, 'controls.MasterLogin.tpl.label.company'),
                    logInLabel: QUILocale.get(lg, 'controls.MasterLogin.tpl.logInLabel'),
                    logBackLabel: QUILocale.get(lg, 'controls.MasterLogin.tpl.logBackLabel'),
                    visibilityTitle: QUILocale.get(lg, 'controls.MasterLogin.tpl.visibilityTitle')
                })
            }).inject(document.body, 'bottom');

            // Register events
            this.fadeInElms = this.$Content.querySelectorAll('.quiqqer-masterlogin--fadeInFromLeft');
            this.LoginBtn = this.$Content.querySelector('.quiqqer-masterlogin-actions-login');
            this.LogBackBtn = this.$Content.querySelector('.quiqqer-masterlogin-actions-logback');
            this.OpenBtn = this.$Content.querySelector('.quiqqer-masterlogin__btnOpen');
            this.CloseBtn = this.$Content.querySelector('.quiqqer-masterlogin__btnClose');

            // Determine initial visibility
            const visible = localStorage.getItem('quiqqer-masterlogin-visibility');

            if (visible === null || visible.toInt() === 1) {
                this.$showContainer();
            } else {
                this.$showOpenBtn();
            }

            // Register action clicks
            this.OpenBtn.addEvent('click', this.$toggleVisibility);
            this.CloseBtn.addEvent('click', this.$toggleVisibility);
            this.LoginBtn.addEvent('click', this.$openUserSelect);

            if (this.getAttribute('slave')) {
                this.LogBackBtn.addEvent('click', this.$openLogBackConfirm);
                this.$Content.addClass('quiqqer-masterlogin--slave');
            }
        },

        /**
         * Toggle masterlogin container visibility
         */
        $toggleVisibility: function () {
            if (this.$animationRunning) {
                return;
            }

            this.$animationRunning = true;

            if (this.$visible) {
                this.$hideContainer().then(() => {
                    this.$showOpenBtn();
                    this.$animationRunning = false;
                });

                return;
            }

            this.$showContainer().then(() => {
                this.$animationRunning = false;
            });

            this.$hideOpenBtn();
        },

        // region animation

        /**
         * Show container with user information
         */
        $showContainer: function () {
            const Container = this.$Content.querySelector('.quiqqer-masterlogin__container');

            this.CloseBtn.style.opacity = 0;
            this.CloseBtn.style.transform = 'scale(0)';

            const animateContainer = new Promise(resolve => {
                animejs({
                    targets: Container,
                    translateX: ['100%', '0'],
                    easing: 'easeOutQuad',
                    duration: 250,
                    complete: resolve
                });
            });

            return new Promise((resolve) => {
                animateContainer.then(() => {
                    animejs({
                        targets: this.fadeInElms,
                        translateX: ['-16px', '0'],
                        opacity: 1,
                        easing: 'easeOutQuart',
                        duration: 400,
                        delay: animejs.stagger(80, {easing: 'easeInQuad'}),

                        complete: () => {
                            this.$visible = true;
                            this.$visible = true;
                            localStorage.setItem('quiqqer-masterlogin-visibility', '1');
                            resolve();
                        }
                    });
                });

                // run this animation simultaneously with small delay
                animejs({
                    targets: this.CloseBtn,
                    scale: ['0', '1.3', '0.85', '1'],
                    opacity: 1,
                    duration: 450,
                    delay: 500,
                    easing: 'linear',
                    complete: () => {
                        this.CloseBtn.style.opacity = null;
                        this.CloseBtn.style.transform = null;
                    }
                });
            });
        },

        /**
         * Hide container with user information
         */
        $hideContainer: function () {
            const Container = this.$Content.querySelector('.quiqqer-masterlogin__container');

            return new Promise((resolve) => {
                animejs({
                    targets: Container,
                    translateX: ['0', '100%'],
                    easing: 'easeOutQuad',
                    duration: 250,

                    complete: () => {
                        this.$visible = false;
                        localStorage.setItem('quiqqer-masterlogin-visibility', '0');

                        this.fadeInElms.forEach((Elm) => {
                            Elm.style.transform = null;
                            Elm.style.opacity = null;
                            resolve();
                        });
                    }
                });
            });
        },

        /**
         * Show toggle button and animate the icon
         */
        $showOpenBtn: function () {
            const Icon = this.OpenBtn.querySelector('.quiqqer-masterlogin__btnOpenIcon');

            Icon.style.opacity = 0;
            Icon.style.transform = 'transform: translateX(10%)';

            animejs({
                targets: this.OpenBtn,
                translateX: ['110%', '0'],
                easing: 'easeOutQuart',
                duration: 400
            });

            animejs({
                targets: Icon,
                translateX: ['1rem', '0'],
                opacity: [0, 1],
                easing: 'easeOutQuart',
                duration: 300,
                delay: 150
            });
        },

        /**
         * Hide toggle button
         */
        $hideOpenBtn: function () {
            animejs({
                targets: this.OpenBtn,
                translateX: '110%'
            });
        },

        // endregion

        // regin popups

        /**
         * Open popup to select slave user
         */
        $openUserSelect: function () {
            new UserSelectPopup({
                events: {
                    onUserSelect: function (userId, Popup) {
                        MasterLoginManager.logInAs(userId).then(function (success) {
                            window.location.reload();
                        });
                    }
                }
            }).open();
        },

        /**
         * Open popup to confirm log back
         */
        $openLogBackConfirm: function () {
            require([
                'text!package/quiqqer/masterlogin/bin/js/frontend/controls/MasterLogin.LogBack.html',
            ], (template) => {
                const self = this,
                    html = Mustache.render(template, {
                        title: QUILocale.get(lg, 'controls.MasterLogin.logback.title'),
                        text: QUILocale.get(lg, 'controls.MasterLogin.logback.question'),
                        currentUserLabel: QUILocale.get(lg, 'controls.MasterLogin.logback.currentUser'),
                        originalUserLabel: QUILocale.get(lg, 'controls.MasterLogin.logback.originalUser'),
                        slaveName: self.SlaveUser.name,
                        slaveId: self.SlaveUser.id,
                        slaveEmail: self.SlaveUser.email,
                        slaveCompany: self.SlaveUser.company,
                        masterName: self.MasterUser.name,
                        masterId: self.MasterUser.id,
                        masterEmail: self.MasterUser.email,
                        masterCompany: self.MasterUser.company,
                        idLabel: QUILocale.get(lg, 'controls.MasterLogin.tpl.label.id'),
                        nameLabel: QUILocale.get(lg, 'controls.MasterLogin.tpl.label.name'),
                        emailLabel: QUILocale.get(lg, 'controls.MasterLogin.tpl.label.email'),
                        companyLabel: QUILocale.get(lg, 'controls.MasterLogin.tpl.label.company'),
                });

                new QUISimpleConfirmWindow({
                    'class': 'quiqqer-masterlogin-logBackConfirm',
                    maxHeight: 600,
                    maxWidth: 700,
                    autoclose: false,
                    contentPadding: false,
                    buttonCancel: {
                        'class': 'btn btn-link-body',
                        icon: false,
                        text: QUILocale.get(lg, 'controls.UserSelectPopup.closeButtonText'),
                    },
                    buttonSubmit: {
                        'class': 'btn btn-primary',
                        icon: 'fa fa-check',
                        text: QUILocale.get(lg, 'controls.MasterLogin.logback.confirm'),
                    },
                    events: {
                        onOpen: function(Win) {
                            let Content = Win.getContent();
                            Content.set('html', html);
                            Win.getElm().querySelector('button[name="close"]').setAttribute(
                                'aria-label',
                                QUILocale.get(lg, 'controls.UserSelectPopup.closeButtonText')
                            );
                        },
                        onSubmit: function (Win) {
                            Win.Loader.show();

                            MasterLoginManager.logBack().then(function () {
                                window.location.reload();
                            }, function () {
                                Win.Loader.hide();
                            });
                        }
                    }

                }).open();
            });
        }

        // endregion
    });
});
