import Browser from "../modules/browser.js";
import SimpleBar from "simplebar";

class NAV {

    constructor(el) {

        // config
        this.breakpoint = 1025;
        this.menuHeight = 52;
        this.isSubmenuOpen = false;

        var context = this;
        this.el = el;
        this.htmlEl = $("html");
        this.masterMenu = this.el.find('#master-menu');
        this.headerMenu = this.el.find('.navbar-header');
        this.stickyMenu = this.el.find('.navbar-default');
        this.gameMenu = this.el.find('#game');
        this.restaurantMenu = this.el.find('#restaurants');
        this.spiritMenu = this.el.find('#spirit');
        this.homeMenu = this.el.find('#homelk');
        this.giftboxMenu = this.el.find('#gift');
        this.menuItems = this.el.find('.menu-item');
        this.accountDropdownDesktop = this.el.find('.my-account');
        this.masterMenuScrollBar = new SimpleBar(this.masterMenu.get(0), {autoHide: false});

        // logo barriere / picto home on sticky
        this.homeLink = this.el.find('.home-link');
        this.homeLinkLc = this.homeLink.find('span:last-child');
        this.homeLinkFc = this.homeLink.find('span:first-child');

        // carreVIP account
        this.spaceCarreVip = this.el.find('.space-carre-vip');
        this.carreVipAccountLogin = this.el.find('.nav-carre-vip-account-login');
        this.carreVipAccountClose = this.el.find('.carre-vip-account-close');

        // Mobile Casino List
        this.casinoListContainer = this.el.find(".js-casinolist-container");

        // Events
        window.addEventListener('resize', this.debounce(this.resize.bind(this), 150));

        // Bootstrap Collapse Events
        this.masterMenu.on('show.bs.collapse', this.onShow.bind(this));
        this.masterMenu.on('shown.bs.collapse', this.onShown.bind(this));
        this.masterMenu.on('hide.bs.collapse', this.onHide.bind(this));
        this.masterMenu.on('hidden.bs.collapse', this.onHidden.bind(this));

        //SubMenu game
        this.gameMenu.on('show.bs.dropdown', this.openMenu.bind(this));
        this.gameMenu.on('hide.bs.dropdown', this.closeMenu.bind(this));

        //SubMenu restaurants
        this.restaurantMenu.on('show.bs.dropdown', this.openMenu.bind(this));
        this.restaurantMenu.on('hide.bs.dropdown', this.closeMenu.bind(this));

        // Submenu gift
        this.giftboxMenu.on('show.bs.dropdown', this.openMenu.bind(this));
        this.giftboxMenu.on('hide.bs.dropdown', this.closeMenu.bind(this));


        // Bind click mobile nav to display always on top
        $('.mega-dropdown, #other-website').click(function (e) {
            var posY = $(this).position().top - context.menuHeight;
            $("#master-menu").animate({scrollTop: posY}, 100, 'swing');
        });

        // Animate Mega Menu
        $('.mega-dropdown').on('show.bs.dropdown', function (e) {
            var windowWidth = window.innerWidth;
            $(this).find('.dropdown-menu').first().stop(true, true).slideDown(300);
            context.toogleMenuSeparators($(this), context);
        });

        $('.mega-dropdown').on('hide.bs.dropdown', function (e) {
            var windowWidth = window.innerWidth;
            $(this).find('.dropdown-menu').first().stop(true, true).slideUp(300);
            $('.mega-dropdown').removeClass('open');
            context.closeMenuSeparators(context);
        });

        //onchange open casinons url via select jquery
        $('.my-account-select').change(function (e) {
            var url = $(this).val();
            if (url != '') {
                location.href = url;
            }
            return false;
        });

        // this.cloneAccountMobile();
        this.cloneWebsitesMobile();
        this.carreVipBoxMobile();
        this.carreVipBox();
        this.shortenAccountMobile();
        this.setEvents();
        this.resize();
        this.logoMobile();
        this.cloneCasinoListMobile();

        /*$('.button-discover-bar-restaurant').on('click', function(e){
         var windowWidth = window.innerWidth;
         if (windowWidth >= context.breakpoint) {
         context.restaurantMenu.find('.dropdown-menu').first().stop(true, true).slideDown(300, function(){
         context.restaurantMenu.addClass('open');
         });
         }
         context.toogleMenuSeparators(context.restaurantMenu, context);
         });*/

    }


    closeMenuSeparators(c) {
        c.restaurantMenu.find('a').removeClass('special');
        c.gameMenu.find('a').removeClass('special');
        c.homeMenu.find('a').removeClass('special');
        c.spiritMenu.find('a').removeClass('special');
        c.giftboxMenu.find('a').removeClass('special');
    }

    toogleMenuSeparators($t, c) {
        var $ch = c.homeMenu.find('a'),
            $cg = c.gameMenu.find('a'),
            $cr = c.restaurantMenu.find('a'),
            $cc = c.giftboxMenu.find('a'),
            $cs = c.spiritMenu.find('a'),
            id = $t.attr('id');

        switch (id) {
            case 'restaurants' :
                $cr.addClass('special');
                $cg.addClass('special');
                $ch.removeClass('special');
                $cc.removeClass('special');
                $cs.removeClass('special');
                break;
            case 'game' :
                $ch.addClass('special');
                $cg.addClass('special');
                $cr.removeClass('special');
                $cc.removeClass('special');
                $cs.removeClass('special');
                break;
            case 'gift' :
                $cc.addClass('special');
                $cs.addClass('special');
                $ch.removeClass('special');
                $cg.removeClass('special');
                $cr.removeClass('special');
                break;
        }
    }


    // Espace Carré VIP -> carré VIP on mobile

    cloneAccountMobile() {

        // clone
        this.accountDropdownMobile = this.accountDropdownDesktop.clone(true);
        this.accountDropdownMobile.appendTo('.navbar-header-account');

        this.carreVip = $('.space-carre-vip').clone(true);
        this.carreVip.appendTo('.navbar-header-carrevip').addClass('space-carre-vip-mobile');

        this.carreVip = $('.hea-casinopass').clone(true);
        this.carreVip.appendTo('.navbar-header-carrevip').addClass('hea-casinopass-mobile');
    }

    cloneWebsitesMobile() {

        var otherWebsite;

        otherWebsite = $(this.el).find('.other-website');
        otherWebsite.clone().appendTo('.others-website-mobile');
    }

    cloneCasinoListMobile() {

        var casinoList;

        casinoList = this.el.find(".my-account-select").clone(true);
        casinoList.addClass("nav-mobile-select-input");
        this.casinoListContainer.prepend(casinoList);
    }

    // close box carre vip mobile

    closeBoxCarreVip(device, c, $e, $e2) {
        $e.hide();
        if ($e2) $e2.removeClass('active');
        return false;
    }

    // open bnox carre vip mobile

    openBoxCarreVip(device, c, $e1, $e2) {
        $e1.show();
        if ($e2) $e2.addClass('active');
        return true;
    }


    reserCarreVipFormValues(box) {
        box.find('input').on('click', function (e) {
            e.preventDefault();
            $(this).attr('value', '');
            if ($(this).attr('id') === 'passwd') $(this).attr('type', 'password');
        });
    }


    // box carre vip desktop

    carreVipBox() {
        var boxCarreVipState = false;
        var context = this;

        this.reserCarreVipFormValues(this.carreVipAccountLogin);

        this.carreVipAccountClose.on('click', function () {
            boxCarreVipState = context.closeBoxCarreVip(false, context, context.carreVipAccountLogin, context.spaceCarreVip);
        });
        this.spaceCarreVip.on('click', function () {
            (boxCarreVipState) ? boxCarreVipState = context.closeBoxCarreVip(false, context, context.carreVipAccountLogin, context.spaceCarreVip)
                : boxCarreVipState = context.openBoxCarreVip(false, context, context.carreVipAccountLogin, context.spaceCarreVip);
        });
        $(window).resize(function () {
            if (boxCarreVipState) boxCarreVipState = context.closeBoxCarreVip(false, context, context.carreVipAccountLogin, context.spaceCarreVip);
        });
    }

    // Box Account Carre VIP Mobile

    carreVipBoxMobile() {
        this.carreVipBoxMobile = $('.nav-carre-vip-account-login-wrapper').clone(true);
        this.carreVipBoxMobile.appendTo('.nav-local').addClass('nav-carre-vip-account-login-wrapper-mobile');

        var $boxCarreVipMobile = $('.nav-carre-vip-account-login-wrapper-mobile');
        var boxCarreVipMobileState = false;
        var context = this;

        this.reserCarreVipFormValues($boxCarreVipMobile);

        $boxCarreVipMobile.find('.carre-vip-account-close').on('click', function () {
            boxCarreVipMobileState = context.closeBoxCarreVip(true, context, $boxCarreVipMobile);
        });
        $('.space-carre-vip-mobile').on('click', function () {
            (boxCarreVipMobileState) ? boxCarreVipMobileState = context.closeBoxCarreVip(true, context, $boxCarreVipMobile)
                : boxCarreVipMobileState = context.openBoxCarreVip(true, context, $boxCarreVipMobile);
        });
        $(window).resize(function () {
            //if(boxCarreVipMobileState) boxCarreVipMobileState = context.closeBoxCarreVip(true, context, $boxCarreVipMobile);
        });
    }

    // shorten account text on mobile

    shortenAccountMobile() {
        var device = this.getCurrentDevice(),
            labelCarreVip = $('.picto-barriere-label'),
            labelMobile = labelCarreVip.attr('data-mobile'),
            labelDesktop = labelCarreVip.attr('data-desktop');

        (device === 'mobile') ? labelCarreVip.text(labelMobile)
            : labelCarreVip.text(labelDesktop);
    }

    // show logo barriere on sticky

    showLogoBarriere(e) {
        (e.data.hl.hasClass('active')) ? e.data.hllc.attr('class', 'home-logo-min') : e.data.hlfc.attr('class', 'home-logo-min');
        e.data.hl.find('a:before').css('top', '35px!important');
    }

    // show picto home on sticky

    showLogoHome(e) {
        (e.data.hl.hasClass('active')) ? e.data.hllc.attr('class', 'home-icon-golden') : e.data.hlfc.attr('class', 'home-icon');
    }

    // show picto home / logo barriere on sticky

    logoMobile() {
        this.stickyMenu.on('sticky-start', {
                hl: this.homeLink,
                hllc: this.homeLinkLc,
                hlfc: this.homeLinkFc
            }, this.showLogoBarriere)
            .on('sticky-end', {hl: this.homeLink, hllc: this.homeLinkLc, hlfc: this.homeLinkFc}, this.showLogoHome);
    }

    // on window resize

    onWindowResize() {
        this.shortenAccountMobile();
    }

    debounce(func, wait, immediate = false) {
        var timeout;

        return function () {
            var context = this, args = arguments;
            var later = function () {
                timeout = null;
                if (!immediate) func.apply(context, args);
            };
            var callNow = immediate && !timeout;
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
            if (callNow) func.apply(context, args);
        };
    }

    getCurrentDevice() {
        return window.getComputedStyle(document.querySelector("body"), "::before").getPropertyValue("content").replace(/"|'/g, '');
    }

    onAccountDropdownShown() {

        var device;

        device = this.getCurrentDevice();
        if (device !== "desktop") {
            this.accountDropdownMobile.find(".my-account-select").focus();
        }
    }

    onShow() {

        // Menu open
        this.setMenuOpen();
    }

    onShown() {

        this.resize();
        this.recalculateMasterMenuScrollBar(120);
    }

    /**
     * Recalculates master menu scrollbar after a defined delay
     * @param {Number} delay - a delay in milliseconds
     */
    recalculateMasterMenuScrollBar(delay) {

      let start = undefined;

      const onAnimationFrame = (timestamp) => {

        if (start === undefined)
        {
          start = timestamp;
        }
        const progress = timestamp - start;

        if (progress >= delay)
        {
          this.masterMenuScrollBar.recalculate();
          return;
        }
        window.requestAnimationFrame(onAnimationFrame);
      };
      window.requestAnimationFrame(onAnimationFrame);
    }

    onHide() {
        // Menu open
        this.setMenuClose();
    }

    onHidden() {
        //console.log("onHidden");
    }

    resize() {

        var windowWidth = window.innerWidth;
        var windowHeight = window.innerHeight;

        if (windowWidth <= this.breakpoint) {

            // Mobile

            // NOTE: fix mantis #3196
            this.masterMenu.css('height', (windowHeight - this.menuHeight) + 'px');

            // Sticky
            this.stickyMenu.unstick();

        } else {

            // Sticky
            this.stickyMenu.sticky({topSpacing: 0});

            // NOTE: fix mantis #3196
            this.masterMenu.css('height', 'auto');

        }
    }

    setMenuOpen() {

        if (!this.headerMenu.hasClass('open'))
        {
            const device = Browser.getCurrentDevice();

            this.headerMenu.addClass('open');
            if (device.type !== "desktop")
            {
              this.htmlEl.addClass("noscroll");
            }
        }
    }

    setMenuClose() {

        if (this.headerMenu.hasClass('open'))
        {
            this.htmlEl.removeClass("noscroll");
            this.headerMenu.removeClass('open');
        }
    }

    openMenu() {

        var device;

        this.menuItems.addClass('isOpen');
        this.onShow();
        device = Browser.getCurrentDevice();
        this.isSubmenuOpen = true;
    }

    closeMenu() {
        this.menuItems.removeClass('isOpen');
        this.onHide();
        this.isSubmenuOpen = false;
    }

    enableScroll() {
        var $body = $('body');
        if ($body.hasClass('noscroll')) $body.removeClass('noscroll');
    }

    disableScroll() {
        var $body = $('body');
        if (!$body.hasClass('noscroll')) $body.addClass('noscroll');
    }

    setEvents() {
        $(window).on("resize.NAV", this.debounce(this.onWindowResize.bind(this), 150));
    }


}
export default NAV;
