'use strict';

angular
    .module('select-group-user', ['zeroclipboard'])

    .controller('SelectGroupUserModal', [
        "$scope", "$uibModalInstance", "APIName", "$rootScope", "checkbox", "AppUtil", "$compile", "session", "type",
        "userConfig", "$stateParams",
        function ($scope, $uibModalInstance, APIName, $rootScope, checkbox, AppUtil, $compile, session, type,
                  userConfig, $stateParams) {
            var user = session.getUser();
            $scope.selectedGroup = [];
            $scope.selectedGroupName = [];
            $scope.selectedEmail = [];
            $scope.isLocalChange = false;
            checkbox.cleanUp();
            if (type === 'name') {
                var params = {};
                if (user.role_id === userConfig.COMPANY_ADMIN.role
                    || user.role_id === userConfig.SUPER_ADMIN.role) {
                    params['team_id'] = $stateParams.team_id;
                }

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

                AppUtil.createRequest(objUrl, params, function (res) {
                    $scope.listGroup = res.data;
                });
            }
            $scope.onClose = function () {

                checkbox.cleanUp();
                $uibModalInstance.close();
            };


            $scope.onAccept = function () {
                //create group user
                if (type === 'name') {
                    angular.forEach($scope.selectedGroup, function (selected) {
                        $scope.selectedGroupName.push(_.filter($scope.listGroup, function (group) {
                            return group.group_user_id === selected
                        })[0]);
                    });
                    $rootScope.$broadcast("select_group_user_name", $scope.selectedGroupName);
                } else {
                    $scope.selectEmailFromGroups($scope.selectedGroup);
                }
                checkbox.cleanUp();
                $uibModalInstance.close();
            };


            $scope.selectEmailFromGroups = function (groupIds) {

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

                $scope.isLocalChange = true;
                AppUtil.createRequest(objUrl,
                    {
                        group_user_ids: groupIds.join(','),
                        team_id: user.team_id
                    },
                    function (res) {
                        $rootScope.$broadcast("select_group_user_email", res.data);
                        $scope.isLocalChange = false;
                    },

                    function (error) {
                        AppUtil.closeToast();
                        $scope.isLocalChange = false;
                    });
            };

            //Create prams for group user list
            function makeParamAddGroupUser(data) {
                var teamId;
                if (user.role_id === userConfig.COMPANY_ADMIN.role
                    || user.role_id === userConfig.SUPER_ADMIN.role) {
                    teamId = $stateParams.team_id;
                } else {
                    teamId = user.team_id
                }
                return {
                    team_id: teamId,
                    search_key: data.search.value.trim(),
                    page_size: data.length,
                    page_number: data.start / data.length + 1,
                    sort_field: data.columns[data.order[0].column].data,
                    asc_sort: data.order[0].dir === "asc"
                };
            }

            // Group address table
            $scope.tableSelectGroupUser;

            // Group address table options
            $scope.optsSelectGroupUser = {
                "order": [2, 'desc'],
                "pageLength": 5,
                "ajax": function (data, callback) {

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

                    $scope.isLocalChange = true;

                    AppUtil.createRequest(objUrl, makeParamAddGroupUser(data), function (res) {
                        var json = {
                            "recordsTotal": res.data.total_elements,
                            "recordsFiltered": res.data.total_elements,
                            "data": []
                        };
                        $.each(res.data.content, function (key, value) {
                            json.data.push({
                                groupUserId: value.group_user_id,
                                groupName: value.name,
                                numberUser: value.number_user
                            });
                        });
                        // Insert value
                        callback(json);
                        $scope.isLocalChange = false;
                    });
                },
                "rowCallback": function (row, data) {

                    $("td:eq(0)", row).addClass("text-center")
                        .html("<input icheck-table type='checkbox' class='icheckbox' role='child-checkbox' " +
                            "id='" + data.groupUserId + "'>");

                    $("td:eq(1)", row).html("<div class='ellipsis' mytip='" + data.groupName + "' mytip-placement='top-left' mytip-show-when ='150'>" + data.groupName + "</div>");


                    $("td:eq(2)", row).addClass("text-center")
                        .html("<div>" + data.numberUser + "</div>");
                },
                "drawCallback": function (s) {

                    // We should use directive to change data & bind event
                    checkbox.bindCheck(s.nTable, function (array) {

                        // We can get the list after items have been checked
                        $scope.selectedGroup = array;

                        // Let it knows
                        $scope.$digest();
                    });

                    // Using compile service
                    $compile(s.nTBody)($scope);
                },
                "columns": [
                    {"data": "groupUserId"},
                    {"data": "groupName"},
                    {"data": "numberUser"}
                ],
                "columnDefs": [
                    {'orderable': false, 'targets': [0]}
                ],
                destroy: true
            };

        }])
    .controller('ShowGroupUserCollaboratorModal', [
        "$scope", "$uibModalInstance", "APIName", "$rootScope", "checkbox", "AppUtil", "$compile", "session",
        "userConfig", "$stateParams", "groupId", "projectId", "folderId", "util",
        function ($scope, $uibModalInstance, APIName, $rootScope, checkbox, AppUtil, $compile, session,
                  userConfig, $stateParams, groupId, projectId, folderId, util) {

            var user = session.getUser();
            $scope.onClose = function () {
                $uibModalInstance.close();
            };


            //Create prams for group user list
            function makeParamGetGroupCollaborator(data) {
                var sortField;
                switch (data.order[0].column) {
                    case 0:
                        sortField = (user.lang === "en") ? "firstName" : "lastName";
                        break;
                    case 1:
                        sortField = "mailAddress";
                        break;
                    case 2:
                        sortField = "role";
                        break;
                }
                return {
                    project_id: projectId,
                    search_key: data.search.value.trim(),
                    page_size: data.length,
                    page_number: data.start / data.length + 1,
                    sort_field: sortField,
                    // sort_field: data.columns[data.order[0].column].data,
                    asc_sort: data.order[0].dir === "asc"
                };
            }

            // Group address table
            $scope.tableSelectGroupUserCollaborator;

            // Group address table options
            $scope.optsSelectGroupUserCollaborator = {
                "order": [2, 'asc'],
                "pageLength": 5,
                "ajax": function (data, callback) {

                    var objUrl = {
                        method: APIName.GET_USERS_PROJECT_GROUP.method,
                        name: APIName.GET_USERS_PROJECT_GROUP.name + folderId + APIName.GET_USERS_PROJECT_GROUP.surfix + groupId
                    };

                    AppUtil.createRequest(objUrl, makeParamGetGroupCollaborator(data), function (res) {
                        var json = {
                            "recordsTotal": res.data.total_elements,
                            "recordsFiltered": res.data.total_elements,
                            "data": []
                        };
                        $.each(res.data.content, function (key, value) {
                            var roleName = "";
                            if (value.project_role_id === 1) {
                                roleName = util.translate("label.user.project_role.owner");
                            } else if (value.project_role_id === 2) {
                                roleName = util.translate("label.user.project_role.editor");
                            } else if (value.project_role_id === 3) {
                                roleName = util.translate("label.user.project_role.viewer");
                            } else if (value.project_role_id === 4) {
                                roleName = util.translate("label.user.project_role.previewer");
                            } else if (value.project_role_id === 5) {
                                roleName = util.translate("label.user.project_role.viewer_uploader");
                            } else if (value.project_role_id === 6) {
                                roleName = util.translate("label.user.project_role.previewer_uploader");
                            } else if (value.project_role_id === 7) {
                                roleName = util.translate("label.user.project_role.uploader");
                            }

                            json.data.push({
                                name: (user.lang === "en") ? value.first_name + " " + value.last_name : value.first_name + " " + value.last_name,
                                email: value.email_address,
                                role: value.project_role_id,
                                roleName: roleName
                            });
                        });
                        // Insert value
                        callback(json);
                        $scope.isLocalChange = false;
                    });
                },
                "rowCallback": function (row, data) {

                    $("td:eq(0)", row).html("<div class='ellipsis' mytip='" + data.name + "' mytip-placement='top-left' mytip-show-when ='150'>" + data.name + "</div>");

                    $("td:eq(1)", row).html("<div class='ellipsis' mytip='" + data.email + "' mytip-placement='top-left' mytip-show-when ='150'>" + data.email + "</div>");

                    // $("td:eq(2)", row).addClass("text-center")
                    //     .html("<div>" + data.role + "</div>");
                    if (data.role === 1) {
                        $("td:eq(2)", row).html("<span class='label label-success'>" + data.roleName + "</span>");
                    } else if (data.role === 2) {
                        $("td:eq(2)", row).html("<span class='label label-primary'>" + data.roleName + "<span>");
                    } else {
                        $("td:eq(2)", row).html("<span class='label label-default'>" + data.roleName + "<span>");
                    }


                },
                "drawCallback": function (s) {

                    // Using compile service
                    $compile(s.nTBody)($scope);
                },
                "columns": [
                    {"data": "name"},
                    {"data": "email"},
                    {"data": "role"}
                ],
                "columnDefs": [
                    // {'orderable': false, 'targets': [0]}
                ],
                destroy: true
            };

        }]);