/// <reference path="../references.js" />

rwthapp.util.initNamespace("templates");

rwthapp.templates.menu = (function () {

    var menuStorage = new rwthapp.Storage("rwthapp.templates.menu");

    var menuEntries = {};

    var currentMenu = {};

    var menuPinned = menuStorage.getItem("menuPinned", false);

    var userName = "";

    var sevenInchLock = false;

    var favoritesTop = true;

    var initMenuLang = function () {

        menuEntries = {
            feeds: { route: '#organisation.feeds', title: rwthapp.langStrings.menu.organisation.feeds, visible: true, icon: 'announcement', anonym: true },
            freshman: { route: '#freshmen', title: rwthapp.langStrings.menu.freshman, visible: true, icon: 'explore', anonym: true },
            campus: {
                title: rwthapp.langStrings.menu.campus.title, submenuKey: 'campus', visible: true, icon: 'assignment', anonym: true, submenu: {
                    schedule: { route: '#organisation.timetable', title: rwthapp.langStrings.menu.organisation.schedule, visible: true, icon: 'schedule', anonym: false },
                    grades: { route: '#campus.studentReport', title: rwthapp.langStrings.menu.organisation.studentReport, visible: true, icon: 'mode_edit', anonym: false },
                    events: { route: '#campus.search?type=courses', title: rwthapp.langStrings.menu.organisation.events, visible: true, icon: 'domain', anonym: true }
                }
            },
            elearning: {
                title: rwthapp.langStrings.menu.elearning.title, submenuKey: 'elearning', visible: true, icon: 'school', anonym: true, submenu: {
                    das: { route: '#das.channelOverview', title: rwthapp.langStrings.menu.elearning.das, visible: true, icon: 'chat', anonym: true },
                    l2p: { route: '#l2p.courseList', title: rwthapp.langStrings.menu.elearning.l2p, visible: true, image: 'L2P_Icon.png', anonym: false },
                    //l2pnews: { route: '#l2p.news', title: rwthapp.langStrings.menu.elearning.l2pnews, visible: true, icon: 'info_outline', anonym: false },
                    quiz: { route: '#l2p.quizOverview', title: rwthapp.langStrings.menu.elearning.quiz, visible: true, image: "Quizz2Go.gif", anonym: false }
                }
            },
            organisation: {
                title: rwthapp.langStrings.menu.organisation.title, submenuKey: 'organisation', visible: true, icon: 'account_balance', anonym: true, submenu: {
                    ub: { route: '#campus.ub', title: rwthapp.langStrings.menu.campus.ub, visible: true, icon: 'local_library', anonym: false },
                    mensa: { route: '#canteen.overview', title: rwthapp.langStrings.menu.campus.mensa, visible: true, icon: 'local_dining', anonym: true },
                    rooms: { route: '#campus.search?type=rooms', title: rwthapp.langStrings.menu.campus.rooms, visible: true, icon: 'location_city', anonym: true },
                    employees: { route: '#campus.search?type=employees', title: rwthapp.langStrings.menu.campus.employees, visible: true, icon: 'perm_contact_calendar', anonym: true },
                }
            },
            favorites: { title: rwthapp.langStrings.menu.favorites.title, submenuKey: 'favorites', visible: true, anonym: true, submenu: true, footer: true },
            feedback: { route: '#feedback', title: rwthapp.langStrings.menu.feedback, visible: true, anonym: true, footer: true },
            settings: { route: '#settings', title: rwthapp.langStrings.menu.settings, visible: true, anonym: true, footer: true },
            information: { route: '#information', title: rwthapp.langStrings.menu.information, visible: true, anonym: true, footer: true }
        };

        return requestServerMenuConfigAndMergeWithClientConfig();
    };

    var ready = function () {

        changeBackbuttonVisibility();

        $('#pinMenu').prop("checked", menuPinned);

        var loginLogout = function () {

            if (rwthapp.tokenManager.isLoginPersonalized()) {

                rwthapp.notifications.showConfirmationDialog(rwthapp.langStrings.menu.logoutWarning, 'OK', rwthapp.langStrings.settings.clearData.confirmationCancel).then(function (userAgreed) {

                    if (userAgreed) {

                        rwthapp.tokenManager.logout().then(function () {

                            rwthapp.connection.requestCache.clear();

                            if (location.hash !== '#home') {

                                rwthapp.navigator.gotoPage("home");
                                return;
                            }

                            initMenu();
                        });
                    }
                });
            } else {
                // Only attempt login with internet connection available
                if (!rwthapp.connection.requestHelper.isInternetConnectionAvailable()) {
                    rwthapp.notifications.showToastLong(rwthapp.localization.getLocalizedString("errors.login.noConnection"));
                } else {
                    // Start login
                    rwthapp.tokenManager.login().then(function () {
                        // Clear cache to avoid showing cached anonymous data
                        rwthapp.connection.requestCache.clear();
                    }).catch(function (error) {
                        // Log error
                        rwthapp.logging.logger.error("Login attempt failed.", error);

                        // Login failed, show error message
                        rwthapp.notifications.showToastLong(rwthapp.localization.getLocalizedString("errors.login.general"));
                    }).then(function () {
                        return getUserData().then(function (data) {
                            $('#welcome').find('center').text(rwthapp.langStrings.menu.greeting + ", " + data);
                        });
                    }).then(function () {
                        // Reload to home page if still on polling page
                        if (rwthapp.navigator.currentPage.target.template === "login") {
                            rwthapp.navigator.gotoPage("home", { _: Date.now() }, false);
                        }
                    });
                }
            }
        };

        if (!rwthapp.tokenManager.isLoginPersonalized()) {

            $('#welcome').click(loginLogout);
        }
        $('#loginlogout').click(loginLogout);

        registerMarkHomeScreenFavorite();

        $('a').click(function () {

            var submenu = $(this).data("submenu");
            var menu = $(this).data("menu");
            var favorite = $(this).data("favorite");

            if (submenu) {

                if (!favoritesTop) {

                    favoritesTop = true;
                }

                if (submenu === 'campus') {

                    currentMenu = $.extend(true, {}, menuEntries.campus.submenu);
                }
                if (submenu === 'elearning') {

                    currentMenu = $.extend(true, {}, menuEntries.elearning.submenu);
                }
                if (submenu === 'organisation') {

                    currentMenu = $.extend(true, {}, menuEntries.organisation.submenu);
                }
                if (submenu === 'favorites') {

                    favoritesTop = false;
                }

                rwthapp.templates.menu.state.submenuOpen = true;
                rwthapp.templates.menu.state.menuCloseable = false;

                initMenu();
                return false;
            }

            if (menu) {

                rwthapp.navigator.resetBlockNavigationForHashChangeOnWindows();

                if (!favoritesTop) {

                    favoritesTop = true;
                }

                // when navigating to current active route close menu when possible
                if (rwthapp.navigator.currentPage.target.hash === $(this).attr("href")) {

                    if (!rwthapp.platformInfo.isTablet()) {

                        $('.my-slide-nav').navdrawer('close');
                    }
                    else {

                        if (!rwthapp.util.isLandscape()) {

                            $('.my-slide-nav').navdrawer('close');
                        }
                        else if(!menuPinned) {

                            $('.my-slide-nav').navdrawer('close');
                        }
                    }

                    return false;
                }
            }

            return true;
        });

        $('#pinMenu').on('change', function () {

            menuPinned = $(this).prop("checked");

            $('.my-slide-nav').navdrawer('reinit', menuPinned);
            $('.my-slide-nav').navdrawer('lockAlwaysVisible', !menuPinned);

            changeBackbuttonVisibility();

            menuStorage.setItem("menuPinned", menuPinned);
        });
    };

    var registerMarkHomeScreenFavorite = function () {

        $('.filled-in').click(function () {

            var favorite = rwthapp.favorites.getRWTHFavorite($(this).data("favoritelink"));

            if ($(this).prop("checked")) {

                favorite.setHomeScreen(true);

                var me = $(this);

                $('.filled-in').each(function (index, obj, param) {

                    if (me[0] !== obj) {

                        $(obj).prop("checked", false);
                    }
                });
            }
            else {

                favorite.setHomeScreen(false);
            }

            initMenu();
        });
    };

    var initMainMenu = function () {

        favoritesTop = true;
        rwthapp.templates.menu.state.submenuOpen = false;
        rwthapp.templates.menu.state.menuCloseable = true;
        initMenu();
    };

    var initMenu = function () {

        if (!rwthapp.templates.menu.state.submenuOpen && rwthapp.templates.menu.state.menuCloseable) {

            currentMenu = $.extend(true, {}, menuEntries);
        }

        if (!favoritesTop) {

            currentMenu = $.extend(true, {}, rwthapp.favorites.getRWTHFavorites());
        }

        renderMenu(currentMenu);
        ready();
    };

    var changeBackbuttonVisibility = function () {
        
            if (menuPinned && !rwthapp.templates.menu.state.submenuOpen && rwthapp.util.isLandscape()) {

                $('#menuBack').css('visibility', 'hidden');
            }
            else {

                $('#menuBack').css('visibility', 'visible');
            }
    };

    var requestServerMenuConfigAndMergeWithClientConfig = function () {

        return rwthapp.connection.api.getMenuConfiguration().then(function (data) {
            
            // merges properties from serverMenu into menuEntries recursivly, this means properties which allready exists in menuEntries will be updated with
            // the information from serverMenu and not overwritten
            $.extend(true, menuEntries, JSON.parse(data));
        });
    };

    var getTabletMenuConfig = function () {

        if (rwthapp.platformInfo.isTablet()) {

            var tablet = { visible: false };

            if (rwthapp.util.isLandscape() && sevenInchLock === false) {

                tablet.visible = true;
            }

            return tablet;
        }

        return null;
    };

    var renderMenu = function (data) {

        var results = {

            name: rwthapp.tokenManager.isLoginPersonalized() ? (userName === "" ? undefined : userName) : undefined,
            isLoginPersonalized: rwthapp.tokenManager.isLoginPersonalized,
            tablet: getTabletMenuConfig(),
            menuItems: [],
            favoritesTopLevel: favoritesTop,
            footerItems: [],
            favoritesItems: [],
            hasFavorites: false,
            hasFooter: false,
            useWavesEffect: rwthapp.options.wavesEffect.isEnabled(),
            rwthLogoPath: rwthapp.util.isCarnival() ? "img/rwth-carnival.svg" : null // TODO replace by server request in background to get "seasonal" logo
        };

        var content = $('#slide-menu-content');

        for (var key in data) {

            // set defaults for disabled and anonym property when they are undefined
            if (data[key].disabled === undefined) {

                data[key].disabled = false;
            }

            if (data[key].anonym === undefined) {

                data[key].anonym = true;
            }

            if (!data[key].anonym && !rwthapp.tokenManager.isLoginPersonalized()) {

                data[key].disabled = true;
            }

            if (!data[key].footer) {

                results.menuItems.push(data[key]);
            }
            else {
                
                results.footerItems.push(data[key]);
                results.hasFooter = true;
            }
        }

        var favorites = null;

        if (favoritesTop && rwthapp.templates.menu.state.submenuOpen === false) {

            favorites = rwthapp.favorites.getFirstThreeRWTHFavoritesAndHomeScreen();

            if (favorites.length > 0) {

                results.hasFavorites = true;

                $.each(favorites, function (index, value) {

                    results.favoritesItems.push(value);
                });
            }
        }

        rwthapp.templateRenderer.render(content, 'menu.common', { menuStructure: results });
        
        if (favoritesTop) {
            
            if (favorites && favorites.length > 0 && favorites[0].isHomeScreen) {
                
                $($(".filled-in")[0]).prop("checked", true);
            }
        }
        else {

            var home = rwthapp.favorites.getRWTHHomeFavorite();

            if (home) {

                $('#favorite' + home.favId).prop("checked", true);
            }

            var swapFavoriteAndPersistAgain = function (route, up) {

                var allFavorites = rwthapp.favorites.getRWTHFavorites(), swapped = false;

                $.each(allFavorites, function (index, value) {

                    if (route === value.route) {

                        if (((up && index > 0) || (!up && index < allFavorites.length - 1)) && !swapped) {

                            var a = up ? index - 1 : index;
                            var b = !up ? index + 1 : index;

                            allFavorites[a] = allFavorites.splice(b, 1, allFavorites[a])[0];
                            swapped = true;
                        }
                    }
                });

                if (swapped) {

                    rwthapp.templateRenderer.render($('#favoritesCollection'), 'menu.favorites', { favorites: rwthapp.favorites.getRWTHFavorites() });
                    registerFavoriteClickEvents();
                    
                    var home = rwthapp.favorites.getRWTHHomeFavorite();

                    if (home) {

                        $('#favorite' + home.favId).prop("checked", true);
                    }

                    registerMarkHomeScreenFavorite();
                }
            };

            var registerFavoriteClickEvents = function () {

                $('#favoritesCollection .rwthapp-favorite-up').click(function () {

                    var route = $(this).parent().find('.rwthapp-favorite-link').attr('href');

                    swapFavoriteAndPersistAgain(route, true);
                });

                $('#favoritesCollection .rwthapp-favorite-down').click(function () {

                    var route = $(this).parent().find('.rwthapp-favorite-link').attr('href');

                    swapFavoriteAndPersistAgain(route);
                });

                $('#favoritesCollection .rwthapp-delete-favorite').click(function () {

                    var favoriteDom = $(this).parent(), route = favoriteDom.find('.rwthapp-favorite-link').attr('href');

                    rwthapp.favorites.removeRWTHFavorite(route);
                    favoriteDom.remove();

                    if (route === rwthapp.navigator.currentPage.target.hash) {
                        
                        rwthapp.util.setFavoriteState(route);
                    }
                });

                $('#removeAllFavorites').click(function () {

                    var refreshCurrentPageFavoritesState = false;

                    if (rwthapp.favorites.isFavoriteAlreadySet(rwthapp.navigator.currentPage.target.hash)) {

                        refreshCurrentPageFavoritesState = true;
                    }

                    rwthapp.favorites.removeAll();

                    rwthapp.templateRenderer.render($('#favoritesCollection'), 'menu.favorites', { favorites: rwthapp.favorites.getRWTHFavorites() });

                    if (refreshCurrentPageFavoritesState) {
                    
                        rwthapp.util.setFavoriteState(rwthapp.navigator.currentPage.target.hash);
                    }
                });
            };
        
            registerFavoriteClickEvents();
        }

            $('#menuBack').css('visibility', 'visible');

            $('#menuBack').click(function () {

                rwthapp.util.backButtonClicked();
            });

            // Hide loading bar
        rwthapp.util.hideLoadingScreen();
    };

    var setMenuPinned = function (menuPinnedState) {

        menuPinned = menuPinnedState;
        menuStorage.setItem("menuPinned", menuPinned);
    };

    var isMenuPinned = function () {

        if (menuStorage.getItem("menuPinned") === null && rwthapp.util.isLandscape() && rwthapp.platformInfo.isTablet()) {

            menuStorage.setItem("menuPinned", true);
            menuPinned = true;
        }

        return menuPinned;
    };

    var getUserData = function () {
        if (rwthapp.tokenManager.isUserLoggedIn() && rwthapp.tokenManager.isLoginPersonalized()) {
            return rwthapp.connection.api.getUserInfo().then(function (data) {

                userName = data.FirstName + ' ' + data.LastName;

                return userName;

            }).catch(function (error) {

                userName = "";

                rwthapp.logging.logger.error("Userinfo could not be retrieved.", error);
            });
        } else {
            // Return resolved promise in either case
            return Promise.resolve();
        }
    };

    var activateSevenInchLock = function (activate) {

        if (activate === true) {
            
            sevenInchLock = true;
        }

        return sevenInchLock;
    };

    return {

        initMenuLang: initMenuLang,
        initMainMenu: initMainMenu,
        initMenu: initMenu,
        setMenuPinned: setMenuPinned,
        changeBackbuttonVisibility: changeBackbuttonVisibility,
        isMenuPinned: isMenuPinned,
        getUserData: getUserData,
        activateSevenInchLock: activateSevenInchLock
    };
})();

rwthapp.templates.menu.state = { menuCloseable: true, submenuOpen: false };