'use strict';

angular.module('user-profile', [])

    .controller('UserProfile', ['$scope', 'session', 'AppUtil', 'APIName', "_", "util", '$state', '$route',
        'userConfig', 'app', '$q', '$window', 'ConsoleType',
        function ($scope, session, AppUtil, APIName, _, util, $state, $route,
                  userConfig, app, $q, $window, ConsoleType) {
            $scope.company_id = session.getUser().company_id;
            $scope.specialCharPattern = app.SPECIAL_CHARS_PATTERN;
            $scope.script_pattern = app.SCRIPT_PATTERN;

            $scope.timezones = [
                {value: -12, name: util.translate("timezone.GMT_-12")},
                {value: -11, name: util.translate("timezone.GMT_-11")},
                {value: -10, name: util.translate("timezone.GMT_-10")},
                {value: -9, name: util.translate("timezone.GMT_-9")},
                {value: -8, name: util.translate("timezone.GMT_-8")},
                {value: -7, name: util.translate("timezone.GMT_-7")},
                {value: -6, name: util.translate("timezone.GMT_-6")},
                {value: -5, name: util.translate("timezone.GMT_-5")},
                {value: -4, name: util.translate("timezone.GMT_-4")},
                {value: -3, name: util.translate("timezone.GMT_-3")},
                {value: -2, name: util.translate("timezone.GMT_-2")},
                {value: -1, name: util.translate("timezone.GMT_-1")},
                {value: 0, name: util.translate("timezone.GMT_0")},
                {value: 1, name: util.translate("timezone.GMT_+1")},
                {value: 2, name: util.translate("timezone.GMT_+2")},
                {value: 3, name: util.translate("timezone.GMT_+3")},
                {value: 4, name: util.translate("timezone.GMT_+4")},
                {value: 5, name: util.translate("timezone.GMT_+5")},
                {value: 6, name: util.translate("timezone.GMT_+6")},
                {value: 7, name: util.translate("timezone.GMT_+7")},
                {value: 8, name: util.translate("timezone.GMT_+8")},
                {value: 9, name: util.translate("timezone.GMT_+9")},
                {value: 10, name: util.translate("timezone.GMT_+10")},
                {value: 11, name: util.translate("timezone.GMT_+11")},
                {value: 12, name: util.translate("timezone.GMT_+12")}
            ];

            $scope.languages = [
                {id: 1, value: "auto", name: util.translate("language.auto")},
                {id: 2, value: "en", name: util.translate("language.en")},
                {id: 3, value: "ja", name: util.translate("language.ja")},
                {id: 4, value: "vi", name: util.translate("language.vi")}
            ];

            var currentUser = session.getUser();

            //this object used to hide unnecessary element from template
            $scope.isAdminRoles = false;
            $scope.isCompanyAdmin = false;


            $scope.isSystemRoles = currentUser.role_id === userConfig.SUPER_ADMIN.role
                || currentUser.role_id === userConfig.COMPANY_ADMIN.role;

            $scope.isJapaneseLanguage = false;
            if (currentUser.role_id === userConfig.ADMIN.role
                || currentUser.role_id === userConfig.SUPER_ADMIN.role
                || currentUser.role_id === userConfig.COMPANY_ADMIN.role) {
                $scope.isAdminRoles = true;
            }

            if (currentUser.role_id === userConfig.COMPANY_ADMIN.role) {
                $scope.isCompanyAdmin = true;
            }

            if (currentUser.lang === 'ja') {
                $scope.isJapaneseLanguage = true;
            }


            function getInfoCompany() {
                if ($scope.isCompanyAdmin) {
                    $scope.companyData = {};
                    $scope.companyData.language = $scope.languages[0];
                    $scope.companyData.timezone = $scope.timezones[0];


                    var api = {
                        method: APIName.GET_COMPANY_INFO.method,
                        name: APIName.GET_COMPANY_INFO.name + currentUser.company_id
                    };

                    AppUtil.createRequest(api, {}, function (data) {
                        $scope.companyData.companyId = data.data.company.id;
                        $scope.companyData.name = data.data.company.name;
                        $scope.companyData.company_create_date = util.formatDateBasedOnDiff(data.data.company.create_date, "", session.getCurrentLanguage(), session.getUser().time_zone);

                        $scope.companyData.first_name = data.data.user.first_name;
                        $scope.companyData.last_name = data.data.user.last_name;
                        $scope.companyData.middle_name = data.data.user.middle_name;
                        $scope.companyData.email_address = data.data.user.mail_address;
                        $scope.companyData.user_create_date = util.formatDateBasedOnDiff(data.data.user.signup_date, "", session.getCurrentLanguage(), session.getUser().time_zone);
                        $scope.companyData.timezone = _.find($scope.timezones, {value: data.data.user.time_zone});
                        $scope.companyData.language = _.find($scope.languages, {value: data.data.user.lang});

                        var cData = $scope.companyData;
                        var orgin = angular.copy(cData);
                        // Watch model to see the change
                        $scope.$watch("companyData", function (newValue) {

                            // Compare input values with orgin values
                            if (angular.equals(newValue, orgin)) {
                                $scope.companyChange = false;
                                return;
                            } else {
                                $scope.companyChange = true;
                                return;
                            }

                        }, true);
                    });
                }
            }

            getInfoCompany();

            $scope.sendConfirmEmail = function () {
                var params = {
                    service_key: ConsoleType.Reseller.type
                }
                AppUtil.createRequest(APIName.USER_CONFIRM_CHANGE_EMAIL, params, function (data) {
                    AppUtil.createToast({
                        text: util.translate("default_toast.send_confirm_email")
                    });
                });
            };

            //GENERATE PIN CODE API
            $scope.generatePinCode = function () {

                AppUtil.createRequest(APIName.GENERATE_PIN_CODE, {}, function (data) {
                    loadUserData();
                });
            };
            //back button account setting

            $scope.doBack = function () {
                if (currentUser.role_id === userConfig.SUPER_ADMIN.role) {
                    $state.go("companyList");
                } else if (currentUser.role_id === userConfig.COMPANY_ADMIN.role) {
                    $state.go("teamList");
                } else {
                    $window.history.back();
                }
            };

            $scope.userData = {};

            // Email notification list
            $scope.userData.notification = [
                {description: "user_setting.email_notification.account_change", value: 1, isShow: true},
                {description: "user_setting.email_notification.encode_file_expired", value: 1, isShow: false},
//                    {description: util.translate("user_setting.email_notification.security_authen"), value: 1}
            ];

            $scope.userData.company_name = "";

            $scope.disable = false;

            $scope.userData.language = $scope.languages[0];

            $scope.userData.timezone = $scope.timezones[0];

            // Only admin can view team profile
            // Do not use this
            if (currentUser.role_id !== 1) {
                $scope.isDisable = true;
            }

            if ($scope.isSystemRoles) {
                //Super Admin does not have team, so we do not need to load Team data
                loadUserData();
            } else {
                // Get team info
                AppUtil.createRequest({
                    name: APIName.GET_TEAM.name + currentUser.team_id,
                    method: "GET"
                }, {}, function (data) {

                    $scope.team = data.data;
                    $scope.team.enable_two_factor = data.data.enable_two_factor;

                    // Using filter instead
                    $scope.userData.company_name = $scope.team.name;

                    // Load user info
                    loadUserData();

                });
            }
            // Load user data info
            $scope.isChange = false;

            function loadUserData() {

                AppUtil.createRequest({
                    method: APIName.GET_USER_PROFILE.method,
                    url: APIName.GET_USER_PROFILE.name + currentUser.user_id
                }, {team_id: currentUser.team_id}, function (data) {

                    // $scope.userData = data.result;
                    var user = data.data.user_info;
                    // Decode html
                    $scope.userData.first_name = user.first_name;
                    $scope.userData.middle_name = (user.middle_name) ? user.middle_name : "";
                    $scope.userData.last_name = user.last_name;
                    $scope.userData.mail_address = user.mail_address;
                    $scope.userData.factor_authen = user.factor_authen;
                    $scope.userData.pin_code = user.pin_code;
                    $scope.userData.timezone = _.find($scope.timezones, {value: user.time_zone});
                    $scope.userData.language = _.find($scope.languages, {value: user.lang});

                    var flag = user.notification_flag;
                    for (var x = 0; x < flag.length; x++) {
                        var c = flag.charAt(x);
                        if (x < $scope.userData.notification.length) {
                            // Put to the list
                            $scope.userData.notification[x].value = parseInt(c);
                        }

                    }

                    var uData = $scope.userData;
                    uData.middle_name = (uData.description === null) ? "" : uData.middle_name;

                    // Cache originF
                    var orgin = angular.copy(uData);
                    $scope.originUser = angular.copy(uData);
                    // Watch model to see the change
                    $scope.$watch("userData", function (newValue) {
                        if (!$scope.userData.timezone) {
                            $scope.userData.timezone = _.find($scope.timezones, {value: user.time_zone});
                        }
                        if (!$scope.userData.language) {
                            $scope.userData.language = _.find($scope.languages, {value: user.lang});
                        }
                        // Compare input values with orgin values
                        $scope.isChange = !angular.equals(newValue, orgin);
                    }, true);
                });
            }

            // Do submit
            $scope.submit = false;


            $scope.updateUserProfile = function (valid) {
                var languageIsChange = false;
                if (!valid)
                    return;

                $scope.submit = true;
                var state = 0, expected = ($scope.change && $scope.isCompanyAdmin && $scope.companyChange) ? 2 : 1;

                // update company admin info
                var showMessage = true;
                var finishCall = [];
                var flag = _.pluck($scope.userData.notification, "value").join("");

                if ($scope.isChange) {
                    var paramsUpdate = {
                        first_name: $scope.userData.first_name,
                        middle_name: $scope.userData.middle_name,
                        last_name: $scope.userData.last_name,
                        time_zone: $scope.userData.timezone.value,
                        language: $scope.userData.language.value,
                        factor_authen: $scope.userData.factor_authen,
                        team_id: currentUser.team_id,
                        notification_flag: flag,
                        service_key: ConsoleType.Reseller.type
                    };
                    // params['user_update_id'] = currentUser.user_id;

                    // Do update
                    finishCall.push(AppUtil.createRequest({
                        url: APIName.EDIT_USER.name + currentUser.user_id,
                        method: APIName.EDIT_USER.method
                    }, paramsUpdate, function (data) {
                        $scope.$emit("$userInfoHasChanged", data.data);

                        loadUserData();
                        $state.go("userProfile", {}, {reload: true});
                        //$route.reload();
                        state = _updateState(state, expected);

                        if ($scope.originUser.language.value !== data.data.lang) {
                            languageIsChange = true;
                        }

                    }, function () {
                        showMessage = false;
                        state = _updateState(state, expected);
                    }));
                }

                // update company info
                if ($scope.isCompanyAdmin && $scope.companyChange) {
                    var params = {
                        company_name: $scope.companyData.name,
                    };

                    var objUrl = {
                        method: APIName.EDIT_COMPANY.method,
                        name: APIName.EDIT_COMPANY.name + $scope.companyData.companyId
                    };

                    finishCall.push(AppUtil.createRequest(objUrl, params, function (data) {
                        // Let the rootScope the user info has been changed
                        $scope.$emit("$companyInfoHasChanged", data.data);
                        getInfoCompany();
                        state = _updateState(state, expected);
                    }, function (data) {
                        showMessage = false;
                        state = _updateState(state, expected);
                    }));
                }

                if (finishCall.length > 0) {
                    $q.all(finishCall).then(function () {

                        if (showMessage) {

                            if (languageIsChange) {
                                //reload page if language changed
                                window.location.reload(true);
                            } else {
                                AppUtil.showSuccess({text: util.translate('default_toast.save_success')});
                            }
                        }
                    });
                }
            };


            function _updateState(value, expected) {
                if (++value === expected) {
                    $scope.submit = false;
                }

                return value;
            }

        }]);
