'use strict';

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

    .controller('MemberProfile', ['$scope', '$stateParams', '$route', 'APIName', 'AppUtil', "_", "util", 'session',
        '$window', 'app', '$state',
        function ($scope, $stateParams, $route, APIName, AppUtil, _, util, session, $window, app, $state) {
            $scope.isJapaneseLanguage = session.isJapanese();
            $scope.script_pattern = app.SCRIPT_PATTERN;
            $scope.isLockout = false;

            $scope.company_id = $stateParams.company_id;
            $scope.team_id = "";
            //list team role
            $scope.roles = [2, 3, 4];
            var listRole =
                [
                    {id: 2, name: util.translate("label.user.system_role.manager")},
                    {id: 3, name: util.translate("label.user.system_role.user")},
                    {id: 4, name: util.translate("label.user.system_role.guest")}
                ];

            // Get role name
            $scope.getRoleName = function (id) {
                if (!angular.isDefined(id) || id === 1)
                    return;
                return _.find(listRole, {id: id}).name;
            };

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

            // Timezones
            $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")}
            ];

            // Languages
            $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")}
            ];

            $scope.userData = {};

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

            $scope.userData.company_name = "";

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

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

            var objUrl = {
                method: APIName.GET_USER_PROFILE.method,
                url: APIName.GET_USER_PROFILE.name + $stateParams.id
            };

            AppUtil.createRequest(objUrl, {'team_id': $stateParams.team_id}, function (data) {

                $scope.isLockout = data.data.account_lockout;
                $scope.isUpdateRole = data.data.user_info.role_id === 1;
                // Decode html
                $scope.userData.user_id = data.data.user_info.user_id;
                $scope.userData.first_name = data.data.user_info.first_name;
                $scope.userData.middle_name = (data.data.user_info.middle_name) ? data.data.user_info.middle_name : "";
                $scope.userData.last_name = data.data.user_info.last_name;
                $scope.userData.mail_address = data.data.user_info.mail_address;
                $scope.userData.create_date = data.data.user_info.signup_date;
                $scope.userData.role = data.data.user_info.role_id;
                $scope.userData.timezone = _.find($scope.timezones, {value: data.data.user_info.time_zone});
                $scope.userData.language = _.find($scope.languages, {value: data.data.user_info.lang});

                //get team id
                $scope.team_id = data.data.user_info.team_id;

                var flag = data.data.user_info.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 origin
                var orgin = angular.copy(uData);

                // Watch model to see the change
                $scope.$watch("userData", function (newValue) {

                    // Compare input values with orgin values
                    if (angular.equals(newValue, orgin)) {
                        $scope.isChange = false;

                    } else {
                        $scope.isChange = true;

                    }

                }, true);
            });
            // Do submit
            $scope.submit = false;

            $scope.updateUserProfile = function (valid) {

                if (!valid)
                    return;

                $scope.submit = true;

                var params = {};

                // params['user_update_id'] = $stateParams.id;
                params['team_id'] = $scope.team_id;
                params['first_name'] = $scope.userData.first_name;
                params['middle_name'] = $scope.userData.middle_name;
                params['last_name'] = $scope.userData.last_name;
                params['time_zone'] = $scope.userData.timezone.value;
                params['language'] = $scope.userData.language.value;
                params['role_id'] = $scope.userData.role;

                var flag = _.pluck($scope.userData.notification, "value").join("");

                params['notification_flag'] = flag;

                var objUrl = {
                    method: APIName.EDIT_USER.method,
                    name: APIName.EDIT_USER.name + $stateParams.id
                };

                // Do update
                AppUtil.createRequest(objUrl, params, function (data) {
                    if (data.status === 200) {
                        AppUtil.createToast({
                            text: util.translate(APIName.EDIT_USER.success_msg),
                            type: 'success'
                        });
                    }
                    // Let the rootScope the user info has been changed
                    //$scope.$emit( "$userInfoHasChanged", data.result );
                    $state.reload();
                    $scope.submit = false;
                }, function (data) {
                    $scope.submit = false;
                    AppUtil.showError({text: util.translate("sever_errors." + data.status)});
                });
            };

            $scope.change = false;

            $scope.confirmUnlockAccount = function () {
                // Show modal
                AppUtil.confirm({
                    title: util.translate("message.confirm_unlock.title"),
                    message: util.translate("message.confirm_unlock.content"),
                    buttons: [{
                        label: util.translate("button.cancel"),
                        cssClass: 'btn btn-warning',
                        action: function (dialog) {
                            dialog.close();
                        }
                    }, {
                        label: util.translate("button.ok"),
                        cssClass: 'btn btn-primary',
                        action: function (dialog) {
                            // Do delete forever
                            $scope.doUnlockAccount();
                            dialog.close();
                        }
                    }]
                });
            };

            $scope.doUnlockAccount = function () {
                var objUrl = {
                    method: APIName.UNLOCK_ACCOUNT.method,
                    url: APIName.UNLOCK_ACCOUNT.name + $stateParams.id + APIName.UNLOCK_ACCOUNT.suffix + "?team_id=" + $stateParams.team_id
                };
                AppUtil.createRequest(objUrl, {}, function () {
                    AppUtil.showSuccess({
                        text: util.translate("default_toast.unlock_success")
                    });
                    $state.reload();
                }, function (error) {
                    AppUtil.showError({text: util.translate("sever_errors." + error.status)});
                });
            };

        }]);
