'use strict';

angular.module('angularJSApp.authorized', [])
    .controller('AuthorizedCtrl', [
        '$scope', 'session', '$rootScope', 'configServer', 'packageUpgrade', 'AppConfig', 'moment', 'TeamStatus',
        'paymentType', 'userConfig', '$cookies',
        function ($scope, session, $rootScope, configServer, packageUpgrade, AppConfig, moment, TeamStatus,
                  paymentType, userConfig, $cookies) {

            $scope.doLogout = function () {
                session.logout();
            };

            // Toggle the side navigation
            $("#sidebarToggle, #sidebarToggleTop").on('click', function (e) {

                $('#content-wrapper').toggleClass('active');
                $('#top_menu').toggleClass('active');

                $("body").toggleClass("sidebar-toggled");
                $(".sidebar").toggleClass("toggled");
                if ($(".sidebar").hasClass("toggled")) {
                    $('.sidebar .collapse').collapse('hide');
                }
                ;
            });

            // Close any open menu accordions when window is resized below 768px
            $(window).resize(function () {
                if ($(window).width() < 768) {
                    $('.sidebar .collapse').collapse('hide');
                }
                ;

                // Toggle the side navigation when window is resized below 480px
                if ($(window).width() < 480 && !$(".sidebar").hasClass("toggled")) {
                    $("body").addClass("sidebar-toggled");
                    $(".sidebar").addClass("toggled");

                    $('#content-wrapper').addClass('active');
                    $('#top_menu').addClass('active');

                    $('.sidebar .collapse').collapse('hide');
                }
                ;
            });

            // Prevent the content wrapper from scrolling when the fixed side navigation hovered over
            $('body.fixed-nav .sidebar').on('mousewheel DOMMouseScroll wheel', function (e) {
                if ($(window).width() > 768) {
                    var e0 = e.originalEvent,
                        delta = e0.wheelDelta || -e0.detail;
                    this.scrollTop += (delta < 0 ? 1 : -1) * 30;
                    e.preventDefault();
                }
            });

            // Scroll to top button appear
            $(document).on('scroll', function () {
                var scrollDistance = $(this).scrollTop();
                if (scrollDistance > 100) {
                    $('.scroll-to-top').fadeIn();
                } else {
                    $('.scroll-to-top').fadeOut();
                }
            });

            // Smooth scrolling using jQuery easing
            $(document).on('click', 'a.scroll-to-top', function (e) {
                var $anchor = $(this);
                $('html, body').stop().animate({
                    scrollTop: ($($anchor.attr('href')).offset().top)
                }, 1000, 'easeInOutExpo');
                e.preventDefault();
            });

            // load information after charge
            $rootScope.$on("load_trial", loadInfo);

            function loadInfo() {
                session.getAuthUser(function (response) {
                    $rootScope.isFreePackage = false;
                    $rootScope.isTrial = false;
                    // store user into session
                    var userProfile = response;

                    console.log("loadInfo", userProfile);

                    service.setUser(userProfile);

                    service.changeLanguage(userProfile.lang);
                    if (userProfile.team_status === TeamStatus.Trial) {
                        $rootScope.isTrial = true;
                        // expiry trial days inform
                        var currentDate = new Date();
                        var teamCreateDate = new Date(userProfile.team_created_date);

                        $rootScope.expiryTrialDays = 0;
                        $rootScope.days = currentDate.getTime() - teamCreateDate.getTime();
                        $rootScope.days = Math.round($rootScope.days / 1000 / 60 / 60 / 24);

                        if ($rootScope.days <= 30) {
                            $rootScope.expiryTrialDays = 30 - $rootScope.days;
                        }
                    }

                    var originName = userProfile.first_name + ' ' + userProfile.last_name;
                    $rootScope.displayName = (originName.length > 15) ? originName.substring(0, 15) + '...' : originName;
                    $rootScope.isTeamAdmin = (userProfile.role_id === userConfig.TEAM_ADMIN.role);
                    $rootScope.isPaymentOnline = (userProfile.payment_type === paymentType.ONLINE);


                    // if (userProfile.package_object.user_price_id === configServer.USER_PRICE_ID_FREE
                    //     && userProfile.package_object.storage_price_id === configServer.STORAGE_PRICE_ID_FREE ||
                    //     userProfile.package_object.user_price_id === configServer.USER_PRICE_ID_FREE_JA
                    //     && userProfile.package_object.storage_price_id === configServer.STORAGE_PRICE_ID_FREE_JA) {
                    //     $rootScope.isFreePackage = true;
                    //     $rootScope.title_package = packageUpgrade.FREE;
                    // }
                    // if (userProfile.package_object.user_price_id === configServer.USER_PRICE_ID_PRO
                    //     && userProfile.package_object.storage_price_id === configServer.STORAGE_PRICE_ID_PRO ||
                    //     userProfile.package_object.user_price_id === configServer.USER_PRICE_ID_PRO_JA
                    //     && userProfile.package_object.storage_price_id === configServer.STORAGE_PRICE_ID_PRO_JA) {
                    //     $rootScope.title_package = packageUpgrade.PRO;
                    // }
                    $rootScope.isPaymentSession = false;
                    // payment method - 0: Online, 1: Offline
                    if (!$rootScope.isPaymentOnline) {
                        if ($rootScope.toState.name === 'teamPayment' || $rootScope.toState.name === 'upgradeAccount') {
                            $state.go("dashboard");
                        }
                    } else {
                        if (userProfile.is_card_empty === true && AppConfig.TURN_ON_ADD_CARD) {
                            if ($rootScope.toState.name !== 'teamPayment') {
                                $state.go("teamPayment");
                            }
                        } else if (userProfile.team_status === TeamStatus.Suspecting) {
                            $rootScope.isPaymentSession = true;
                            //get expiated date of payment team
                            Util.createRequest(configServer.API_URL + "/payments/team/" + userProfile.team_id,
                                "GET", {}, function (response) {
                                    var status = response.status;
                                    if (status === 200) {
                                        var now = moment(new Date(), 'DD/MM/YYYY');
                                        var expiryDate = moment(new Date(response.data.expiry_date), 'DD/MM/YYYY');
                                        $rootScope.countDays = AppConfig.EXPIRY_DAYS_NOTIFICATION - now.diff(expiryDate, 'days');
                                    } else {
                                        Util.createToast({
                                            className: 'danger',
                                            content: 'SERVER_ERROR.' + status
                                        });
                                    }
                                }, function (errResponse) {
                                    Util.createToast({
                                        className: 'danger',
                                        content: 'SERVER_ERROR.' + errResponse.status
                                    });
                                });
                        }
                    }
                    if ($rootScope.toState.name === 'login') {
                        $state.go("dashboard");
                    }
                    defer.resolve(userProfile);
                }, function (errResponse) {
                    // clear user into session
                    $cookies.remove(AppConfig.TOKEN_COOKIE_NAME);
                    localStorage.removeItem(AppConfig.TOKEN_COOKIE_NAME);

                    $state.go('login');
                    defer.reject(errResponse);
                }, true);
            }

            $scope.goToAdminConsole = function () {
                var token = localStorage.getItem(AppConfig.TOKEN_COOKIE_NAME);
                window.open(
                    configServer.ADMIN_CONSOLE_URL + '?tok=' + token, "_blank");
            }
        }
    ]);
