'use strict';

angular.module('myAccount', [])
    .controller('MyAccountCtrl', [
        '$scope', '$state', 'ngToast', '$timeout', 'AppConfig', 'session', 'Util', 'Patterns', '$uibModal',
        'configServer', 'userConfig',
        function ($scope, $state, ngToast, $timeout, AppConfig, session, Util, Patterns, $uibModal,
                  configServer, userConfig) {
            $scope.currentUser = {};
            $scope.submitting = false;
            $scope.currencySubmitting = false;
            $scope.isTeamAdmin = false;
            $scope.paymentOnline = 0;
            $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 = [
                {value: "auto", name: Util.translate('language.AUTO')},
                {value: "en", name: Util.translate('language.EN')},
                {value: "vi", name: Util.translate("language.VI")},
                {value: "ja", name: Util.translate("language.JA")},
            ];

            $scope.currencies = [
                {value: "YEN", name: Util.translate("CURRENCY.YEN")},
                {value: "USD", name: Util.translate("CURRENCY.USD")}
            ];

            $scope.script_pattern = Patterns.SCRIPT_PATTERN;

            $scope.currentUser = session.getUser();
            $scope.paymentOnline = session.getUser().payment_type;

            loadUserData();

            function loadUserData() {
                Util.createRequest(configServer.API_URL + "/users/" + $scope.currentUser.user_id, "GET",
                    {team_id: $scope.currentUser.team_id}, function (response) {
                        var status = response.status;
                        $scope.data = response.data.user_info;
                        if (status === 200) {
                            $scope.userInfo = {
                                full_name: "",
                                first_name: $scope.data.first_name,
                                last_name: $scope.data.last_name,
                                timezone: _.find($scope.timezones, {value: $scope.data.time_zone}),
                                lang: _.find($scope.languages, {value: $scope.data.lang})
                            };
                            if ($scope.data.lang === "ja") {
                                $scope.userInfo.full_name = $scope.data.last_name + " " + $scope.data.first_name
                            } else {
                                $scope.userInfo.full_name = $scope.data.first_name + " " + $scope.data.last_name
                            }

                            if ($scope.data.role_id === userConfig.TEAM_ADMIN.role) {
                                $scope.isTeamAdmin = true;
                            }

                            var uData = $scope.userInfo;
                            // Cache origin
                            $scope.orgin = angular.copy(uData);
                            // Watch model to see the change
                            $scope.$watch("userInfo", function (newValue) {
                                // Compare input values with orgin values
                                $scope.isChange = !angular.equals(newValue, $scope.orgin);

                            }, true);
                        } else {
                            Util.createToast({
                                className: 'danger',
                                content: 'SERVER_ERROR.' + status
                            });
                        }
                    }, function (error) {
                        Util.createToast({
                            className: 'danger',
                            content: 'SERVER_ERROR.' + error.status
                        });
                    });
            }

            $scope.updateMyAccount = function (valid) {
                $scope.submitting = true;
                if (!valid) {
                    return;
                }
                var params = {
                    first_name: $scope.userInfo.first_name,
                    last_name: $scope.userInfo.last_name,
                    time_zone: $scope.userInfo.timezone.value,
                    language: $scope.userInfo.lang.value,
                    team_id: $scope.currentUser.team_id
                };
                Util.createRequest(configServer.API_URL + "/users/" + $scope.currentUser.user_id, "PUT", params, function (response) {
                    if (response.status === 200) {
                        $scope.$emit("$userInfoHasChanged", response.data);
                        $scope.submitting = false;
                        $scope.isChange = false;
                        loadUserData();
                        Util.createToast({
                            className: 'success',
                            content: 'COMMON.MESSAGE.SAVE_SUCCESS'
                        });
                        $state.go("myAccount", {}, {reload: true});
                    } else {
                        Util.createToast({
                            className: 'danger',
                            content: 'SERVER_ERROR.' + response.status
                        });
                    }
                }, function (error) {
                    Util.createToast({
                        className: 'danger',
                        content: 'SERVER_ERROR.' + error.status
                    });
                });

            };

            $scope.openChangePasswordModal = function () {
                var modalInstance = $uibModal.open({
                    templateUrl: 'components/modal-template/change_password_modal.html',
                    size: 'md',
                    backdrop: 'static',
                    controller: ['$scope', '$rootScope', '$uibModalInstance', '$translate', '$cookies', 'AppConfig',
                        'session', '$http', '$state', 'AppUtil', 'configServer',
                        function ($scope, $rootScope, $uibModalInstance, $translate, $cookies, AppConfig,
                                  session, $http, $state, AppUtil, configServer) {
                            $scope.passwordPolicies = {};
                            $scope.getPasswordPolicySetting = function () {
                                var params = {
                                    auth_token: session.getAccessToken()
                                };
                                Util.createRequest(configServer.API_URL + "/team/settings/password_policy",
                                    "GET", params, function (response) {
                                        $scope.passwordPolicies = JSON.parse(response.data.password_setting);
                                        $scope.password_pattern = $scope.passwordPolicies.regex;
                                        $scope.notificationError = AppUtil.getPasswordPolicyError($scope.passwordPolicies);
                                    }, function (error) {
                                        Util.createToast({
                                            className: 'danger',
                                            content: 'SERVER_ERROR.401'
                                        });
                                        $uibModalInstance.close();
                                        $state.go('login');
                                    });
                            }
                            $scope.getPasswordPolicySetting();

                            $scope.onClose = function () {
                                $uibModalInstance.close();
                            };
                            $scope.dataChange = {
                                currentPass: "",
                                newPass: "",
                                confirmPass: ""
                            };

                            $scope.verifyChangePassword = function (valid) {
                                if (!valid) {
                                    return;
                                }
                                session.getAuthUser(function (data) {
                                    var userId = data.user_id;
                                    var params = {
                                      // old_password: AESEncrypter.encode($scope.dataChange.currentPass),
                                      // new_password: AESEncrypter.encode($scope.dataChange.newPass),
                                      // confirm_password: AESEncrypter.encode($scope.dataChange.confirmPass)
                                      old_password: Util.MD5($scope.dataChange.currentPass),
                                      new_password: Util.MD5($scope.dataChange.newPass),
                                      confirm_password: Util.MD5($scope.dataChange.confirmPass),
                                    };
                                    Util.createRequest(configServer.API_URL + "/users/" + userId + "/password", "PUT", params, function (response) {
                                        if (response.status === 200) {
                                            Util.createToast({
                                                className: 'success',
                                                content: 'COMMON.MESSAGE.SAVE_SUCCESS'
                                            });
                                            $uibModalInstance.close();
                                            localStorage.removeItem(AppConfig.TOKEN_COOKIE_NAME);
                                            sessionStorage.removeItem(AppConfig.USER_FOLDER_ID);
                                            $state.go('login');
                                        } else {
                                            Util.createToast({
                                                className: 'danger',
                                                content: 'SERVER_ERROR.' + response.status
                                            });
                                        }
                                    }, function (err) {
                                        Util.createToast({
                                            className: 'danger',
                                            content: 'SERVER_ERROR.' + err.status
                                        });
                                    });
                                });
                            };
                        }]
                }).result.catch(function (resp) {
                    if (['cancel', 'backdrop click', 'escape key press'].indexOf(resp) === -1) throw resp;
                });
            };

            $scope.openChangeEmailModal = function () {
                return $uibModal.open({
                    templateUrl: 'components/modal-template/confirm_active_modal.html',
                    size: 'md',
                    backdrop: 'static',
                    controller: ['$scope', '$rootScope', '$uibModalInstance', '$translate', '$cookies', 'AppConfig',
                        'session', '$http', '$state', 'AppUtil', 'configServer',
                        function ($scope, $rootScope, $uibModalInstance, $translate, $cookies, AppConfig,
                                  session, $http, $state, AppUtil, configServer) {

                            $scope.opts = {
                                title: Util.translate("USER.CHANGE_EMAIL.TITLE"),
                                message: Util.translate("USER.CHANGE_EMAIL.MSG"),
                                lblAccept: Util.translate("COMMON.BUTTON_OK"),
                                lblDismiss: Util.translate("COMMON.BUTTON_CANCEL")
                            };

                            $scope.onClose = function () {
                                $uibModalInstance.close();
                            };
                            $scope.onAccept = function () {
                                var params = {
                                    outlook: true
                                };
                                Util.createRequest(configServer.API_URL + "/auth/user/email", "POST", params, function (response) {
                                    if (response.status === 200) {
                                        Util.createToast({
                                            className: 'success',
                                            content: 'USER.MY_ACCOUNT.SEND_CONFIRM_EMAIL'
                                        });
                                    }
                                    $uibModalInstance.close();
                                }, function (error) {
                                    Util.createToast({
                                        className: 'danger',
                                        content: 'SERVER_ERROR.' + error.status
                                    });
                                    $uibModalInstance.close();
                                });
                            };
                        }]
                });
            };

            $scope.goBack = function () {
                window.history.back();
            };

            $scope.openConfirmDeleteAccount = function () {
                //show confirm revoke
                var modalInstance = $uibModal.open({
                    templateUrl: 'components/modal-template/confirm_delete_account_modal.html',
                    size: 'md',
                    controller: ['$scope', '$uibModalInstance', 'AppUtil', 'Util', 'configServer', '$state',
                        function ($scope, $uibModalInstance, AppUtil, Util, configServer, $state) {

                            $scope.opts = {
                                title: Util.translate("USER.DELETE_ACCOUNT.TITLE"),
                                message: Util.translate("USER.DELETE_ACCOUNT.MSG"),
                                confirmPasswordLabel: Util.translate("USER.DELETE_ACCOUNT.CONFIRM_PASSWORD_LABEL"),
                                btnAccept: Util.translate("COMMON.BUTTON_OK"),
                                btnCancel: Util.translate("COMMON.BUTTON_CANCEL")
                            };

                            $scope.currentPassword = "";

                            $scope.onClose = function () {
                                $uibModalInstance.close();
                            };

                            $scope.doDeleteAccount = function (valid) {
                                if (!valid) {
                                    return;
                                }
                                var params = {
                                    password_hash: AESEncrypter.encode(Util.MD5($scope.currentPassword))
                                };
                                Util.createRequest(configServer.API_URL + "/teams/cancel_subscription",
                                    "DELETE", params, function (response) {
                                        if (response.status === 200) {
                                            Util.createToast({
                                                className: 'success',
                                                content: 'COMMON.MESSAGE.REQUEST_SUCCESS'
                                            });
                                            $uibModalInstance.close();
                                        } else {
                                            Util.createToast({
                                                className: 'danger',
                                                content: 'SERVER_ERROR.' + response.status
                                            });
                                        }
                                    }, function (error) {
                                        // toast fail
                                        Util.createToast({
                                            className: 'danger',
                                            content: 'SERVER_ERROR.' + error.status
                                        });
                                    });
                            };
                        }]
                }).result.catch(function (resp) {
                    if (['cancel', 'backdrop click', 'escape key press'].indexOf(resp) === -1) throw resp;
                });

                return modalInstance;
            };

            function loadCurrencyData() {
                Util.createRequest(configServer.API_URL + "/teams/" + $scope.currentUser.team_id, "GET",
                    {}, function (response) {
                        var status = response.status;
                        var dataRes = response.data;
                        if (status === 200) {
                            $scope.currency = _.find($scope.currencies, {value: dataRes.currency});
                            // Cache origin
                            $scope.orgin = angular.copy($scope.currency);
                            // Watch model to see the change
                            $scope.$watch("currency", function (newValue) {
                                // Compare input values with orgin values
                                $scope.isChangeCurrency = !angular.equals(newValue, $scope.orgin);

                            }, true);
                        } else {
                            Util.createToast({
                                className: 'danger',
                                content: 'SERVER_ERROR.' + status
                            });
                        }
                    }, function (error) {
                        Util.createToast({
                            className: 'danger',
                            content: 'SERVER_ERROR.' + error.status
                        });
                    });
            }

            loadCurrencyData();

            $scope.$on("load_data_currency", loadDataCurrency);

            function loadDataCurrency(event, value) {
                $scope.isChangeCurrency = false;
                loadCurrencyData();
            }
            $scope.$on("is_loading_spinner", isLoadingSpinner);

            function isLoadingSpinner(event, value) {
                $scope.currencySubmitting = true;
            }

            $scope.$on("not_loading_spinner", notLoadingSpinner);

            function notLoadingSpinner(event, value) {
                $scope.currencySubmitting = false;
            }

            $scope.openConfirmUpdateCurrency = function () {
                var params = {
                    currency: $scope.currency.value
                };
                return $uibModal.open({
                    backdrop: 'static',
                    keyboard: false,
                    templateUrl: 'components/modal-template/confirm_delete_modal.html',
                    controller: ['$scope', '$uibModalInstance', '$translate', '$rootScope', function ($scope, $uibModalInstance, $translate, $rootScope) {
                        $translate(['COMMON.BUTTON_CANCEL', 'COMMON.BUTTON_OK', 'USER.MY_ACCOUNT.CURRENCY_MODAL', 'USER.MY_ACCOUNT.CURRENCY_MSG']).then(function (translations) {

                            $scope.opts = {
                                title: translations['USER.MY_ACCOUNT.CURRENCY_MODAL'],
                                message: translations['USER.MY_ACCOUNT.CURRENCY_MSG'],
                                lblAccept: translations['COMMON.BUTTON_OK'],
                                lblDismiss: translations['COMMON.BUTTON_CANCEL']
                            };

                            $scope.onClose = function () {
                                $uibModalInstance.close();
                            };

                            $scope.onAccept = function () {
                                $rootScope.$broadcast("is_loading_spinner");
                                Util.createRequest(configServer.API_URL + "/teams/" + $scope.currentUser.team_id, "PUT", params, function (response) {
                                    if (response.status === 200) {
                                        loadCurrencyData();
                                        Util.createToast({
                                            className: 'success',
                                            content: 'COMMON.MESSAGE.SAVE_SUCCESS'
                                        });
                                    } else {
                                        Util.createToast({
                                            className: 'danger',
                                            content: 'SERVER_ERROR.' + response.status
                                        });
                                    }
                                    $rootScope.$broadcast("load_data_currency");
                                    $rootScope.$broadcast("not_loading_spinner");
                                }, function (error) {
                                    $rootScope.$broadcast("load_data_currency");
                                    $rootScope.$broadcast("not_loading_spinner");
                                    Util.createToast({
                                        className: 'danger',
                                        content: 'SERVER_ERROR.' + error.status
                                    });
                                });
                                $uibModalInstance.close();
                            }
                        });
                    }]
                });
            };
        }
    ]);
