'use strict';

angular.module('team-member-create', [])

    .controller('CreateTeamMember', ['$scope', '$state', 'AppUtil', 'APIName', 'session', 'APIStatus', "app", "_",
        "util", 'error', '$', '$stateParams', '$window', '$uibModal', 'configServer',
        function ($scope, $state, AppUtil, APIName, session, APIStatus, app, _,
                  util, error, $, $stateParams, $window, $uibModal, configServer) {

            $scope.getPasswordPolicySetting = function () {
                var params = {
                    team_id: $stateParams.team_id,
                    type: 3,
                };
                var objUrlPasswordPolicy = {
                    method: APIName.GET_TEAM_SETTING_BY_TYPE.method,
                    url: APIName.GET_TEAM_SETTING_BY_TYPE.name
                };
                AppUtil.createRequest(objUrlPasswordPolicy, params, function (data) {
                    var passwordPolicy = JSON.parse(data.data.password_setting);
                    $scope.password_pattern = passwordPolicy.regex;
                    $scope.pw_max_length = passwordPolicy.max;
                    $scope.password_error = AppUtil.getPasswordPolicyError(passwordPolicy);
                }, function (error) {
                    AppUtil.showError({text: util.translate("sever_errors." + error.status)});
                    $window.history.back();
                });
            };
            $scope.getPasswordPolicySetting();

            $scope.script_pattern = app.SCRIPT_PATTERN;

            $scope.team_id = $stateParams.team_id;
            $scope.company_id = $stateParams.company_id;
            $scope.pattern = app.EMAIL_PATTERN;

            $scope.tags = [];
            $scope.fileTemplatePath = (session.getCurrentLanguage() === 'ja') ? "data/CSVFile_Template_Import_User_JA.csv" : "data/CSVFile_Template_Import_User.csv";
            var param = {
                file_name: 'CSVFile_Template_Import_User.csv', require_auth: false // Skip authen
            };

            //list role for create new user
            $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")}
            ];

            // Detect language to change order first name, last name
            if (session.getCurrentLanguage() === 'ja') {
                $('#ja-language-name').show();
                $('#en-language-name').hide();
                // Update template download
                param.file_name = 'CSVFile_Template_Import_User_JA.csv';
            } else {
                $('#ja-language-name').hide();
            }
            // Handle download file
            $scope.downloadCsv = function () {
                var url = 'api/download/files/csv/template' + '?' + $.param(param);
                $.fileDownload(url, {httpMethod: 'get'});
            };
            // Get role name
            $scope.getRoleName = function (id) {
                if (!angular.isDefined(id))
                    return;

                return _.find(listRole, {id: id}).name;
            };

            // Do submit create new user
            $scope.submit = false;
            $scope.createUser = function (valid) {

                if (!valid)
                    return;
                $scope.userGroups = "";
                if ($scope.user.groups) {
                    for (var i = 0; i < $scope.user.groups.length; i++) {
                        if (i === $scope.user.groups.length - 1) {
                            $scope.userGroups = $scope.userGroups.concat($scope.user.groups[i].name);

                        } else {
                            $scope.userGroups = $scope.userGroups.concat($scope.user.groups[i].name, ",");
                        }
                    }
                }

                $scope.submit = true;

                // Prevent submit when no change
                var params = APIName.CREATE_USER.params || {};

                params['first_name'] = $scope.first_name;
                params['last_name'] = $scope.last_name;
                params['mail_address'] = $scope.mail_address;
                params['password'] = AESEncrypter.encode($scope.password);
                params['confirm_password'] = AESEncrypter.encode($scope.confirm_password);
                params['role_id'] = $scope.user.role;
                params['team_id'] = $scope.team_id;
                params['group_names'] = $scope.userGroups;
                params['ignore'] = ($scope.override === 1);

                // call Create Project ajax
                AppUtil.createRequest(APIName.CREATE_USER.name, params, function (data) {
                    AppUtil.showSuccess({
                        text: util.translate("default_toast.create_success")
                    });

                    $state.go("adminTeamProfile", {company_id: $stateParams.company_id, id: $stateParams.team_id});
                    $scope.submit = false;

                }, function (error) {
                    AppUtil.showError({
                        text: util.translate("sever_errors." + error.status)
                    });
                    $scope.submit = false;
                });
            };

            //import users from csv file
            $scope.uploadApi = APIName.CREATE_USER_FROM_CSV;
            $scope.importCSVUrl = configServer.BACKEND_API_URL + APIName.CREATE_USER_FROM_CSV.name + "?auth_token=" + session.getToken() + "&team_id=" + $stateParams.team_id;

            $scope.onSuccess = function (data) {
                var results = data.result;
                var status = data.status;
                var message = "";
                if (results.length > 0 && status === APIStatus.OK) {
                    for (var i = 0; i < results.length; i++) {
                        message += results[i].mail_address + "\n";
                    }
                    AppUtil.confirm({
                        title: util.translate("message.email_exist_error.title"),
                        message: message + "\n" + util.translate("message.email_exist_error.content"),
                        buttons: [{
                            label: util.translate("button.ok"),
                            cssClass: 'btn btn-warning',
                            action: function (dialog) {
                                dialog.close();
                            }
                        }]
                    });
                } else if (status === APIStatus.OK) {
                    AppUtil.showSuccess({
                        text: util.translate("default_toast.create_success")
                    });

                    $scope.$apply(function () {
                        $state.go("adminTeamProfile", {company_id: $stateParams.company_id, id: $stateParams.team_id});
                    });

                } else {
                    AppUtil.showError({
                        text: util.translate("sever_errors." + status)
                    })
                }
            };
            $scope.onError = function (error) {
            };

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

            // For tags
            $scope.tagTransform = function (newTag) {
                if (newTag.toString().indexOf(",") !== -1 || newTag.toString().indexOf("<") !== -1) {
                    $scope.isError = true;
                } else {
                    // validate group name length (max 64 chars)
                    if (newTag.length > app.MAX_LENGTH_GROUP_NAME) {
                        $scope.isError = true;
                        $scope.mgs = util.translate('errors.name_too_long').replace('%d', app.MAX_LENGTH_GROUP_NAME);
                    } else {

                        if (newTag)

                            $scope.isError = false;
                        var obj = _.find($scope.tags, {value: newTag});
                        if (!angular.isDefined(obj)) {
                            if (!_.include($scope.user.groups, newTag)) {
                                var item = {
                                    value: newTag,
                                    name: newTag
                                };
                                return item;
                            }
                        }
                    }
                }
            };

            $scope.getTags = function (search) {
                return $scope.tags;
            };
// Show select group user modal
            $scope.showGroupUserModal = function () {
                return $uibModal.open({
                    windowClass: 'bootstrap-dialog type-primary',
                    // backdrop: false,
                    templateUrl: 'js/components/invite/select_group_user_modal.html',
                    controller: 'SelectGroupUserModal',
                    resolve: {
                        type: function () {
                            return 'name';
                        },
                    }
                });
            };

            var handleSelectGroupUserName = function (event, value) {
                if (!$scope.user.groups) {
                    $scope.user.groups = [];
                }
                _.each(value, function (group) {
                    if (!_.find($scope.user.groups, {value: group.name})) {
                        if (!_.include($scope.groupName, group.name)) {
                            var tag = {
                                value: group.name,
                                name: group.name
                            };
                            $scope.user.groups.push(tag);
                        }
                    }
                })
            };

            $scope.$on("select_group_user_name", handleSelectGroupUserName);

            var objUrl = {
                method: APIName.GROUP_USER_LIST_ALL.method,
                name: APIName.GROUP_USER_LIST_ALL.name
            };

            AppUtil.createRequest(objUrl, {team_id: $stateParams.team_id}, function (res) {
                angular.forEach(res.data, function (value) {
                    $scope.tags.push({
                        value: value.name,
                        name: value.name
                    });
                });
            })

            $('#link_password').on('keypress', function(e) {if (e.which === 32) return false;});

        }])
;
