'use strict';
angular.module('team-list', ['ngFileSaver'])

    .controller('TeamList', ['$scope', '$state', 'AppUtil', 'APIName', '$', 'session', '$compile', 'checkbox',
        'util', '$http', 'FileSaver', 'sortPage', 'app', 'configServer',
        function ($scope, $state, AppUtil, APIName, $, session, $compile, checkbox,
                  util, $http, FileSaver, sortPage, app, configServer) {

            $scope.sessionToken = session.getToken();

            // Create params for project list
            function makeParam(data) {
                return {
                    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"
                };
            }

            var userPagingSettings = JSON.parse(localStorage.getItem(sortPage.TEAM_LIST));
            if (!userPagingSettings) {
                userPagingSettings = {
                    search_key: "",
                    page_size: app.LIST_PAGE_SIZE,
                    page_number: 1,
                    display_start: 0,
                    sort_key: 3,
                    asc_sort: false
                }
            }

            // Datatable obj
            $scope.table;

            // Selected items
            $scope.selectedItems = [];

            // Datatable options
            $scope.opts = {
                "order": [
                    userPagingSettings.sort_key,
                    userPagingSettings.asc_sort ? "asc" : "desc"
                ],
                "search": {
                    "search": userPagingSettings.search_key
                },
                pageLength: userPagingSettings.page_size,
                displayStart: userPagingSettings.display_start,
                "ajax": function (data, callback) {

                    var storeParams = {
                        search_key: "",
                        page_size: data.length,
                        display_start: 0,
                        sort_key: data.order[0].column,
                        page_number: data.start / data.length + 1,
                        asc_sort: data.order[0].dir === "asc"
                    };

                    var params = {
                        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"
                    };

                    AppUtil.createRequest(APIName.GET_TEAM_LIST, params, function (data) {
                        var json = {
                            "recordsTotal": data.data.total_elements,
                            "recordsFiltered": data.data.total_elements,
                            "data": []
                        };

                        localStorage.setItem(sortPage.TEAM_LIST, JSON.stringify(storeParams));

                        $.each(data.data.content, function (key, value) {
                            var status = "";
                            if (value.status === 1) {
                                status = util.translate("status.team.active");
                            }
                            if (value.status === 2) {
                                status = util.translate("status.team.delete");
                            }
                            if (value.status === 5) {
                                status = util.translate("status.team.pending");
                            }
                            if (value.status === 6) {
                                status = util.translate("status.team.trial");
                            }
                            if (value.status === 7) {
                                status = util.translate("status.team.suspecting");
                            }
                            json.data.push({
                                team_id: value.team_id,
                                name: value.name,
                                mailAddress: value.email_address,
                                createdDate: value.create_date,
                                status: status,
                                team_status: value.status,
                                code: value.pricing_package ? value.pricing_package.code : '',
                                consoleType: value.pricing_package ? value.pricing_package.type : ''
                            });
                        });
                        // Insert value
                        callback(json);
                    });
                },
                "rowCallback": function (row, data) {
                    if (data.team_status === 2) {
                        $("td:eq(0)", row).addClass("text-center").html("<span></span>");
                    } else {
                        $("td:eq(0)", row).addClass("text-center").html("<input icheck-table type='checkbox' class='icheckbox' role='child-checkbox' id='" + data.team_id + "'>");
                    }
                    $("td:eq(1)", row).html("<a ui-sref='adminTeamProfile({company_id: \"" + session.getUser().company_id + "\",id: \"" + data.team_id + "\"})' class='name' ng-click='removeTab()'><span>" + data.name + "</span></a>");
                    $("td:eq(2)", row).html("<div>" + data.mailAddress + "</div>");
                    $("td:eq(3)", row).addClass("hidden-sm-phone hidden-xs hidden-sm").html("<div>" + util.formatDateBasedOnDiff(data.createdDate, "", session.getCurrentLanguage(), session.getUser().time_zone) + "</div>");
                    if (data.team_status === 1) {
                        $("td:eq(4)", row).html("<span class='label label-success'>" + data.status + "</span>");
                    } else if (data.team_status === 2) {
                        $("td:eq(4)", row).html("<span class='label label-danger'>" + data.status + "</span>");
                    } else if (data.team_status === 5) {
                        $("td:eq(4)", row).html("<span class='label label-warning'>" + data.status + "</span>");
                    } else if (data.team_status === 7) {
                        $("td:eq(4)", row).html("<span class='label label-primary'>" + data.status + "</span>");
                    } else {
                        $("td:eq(4)", row).html("<span class='label' style='background-color:#cba00d;'>" + data.status + "</span>");
                    }
                    $("td:eq(5)", row).html("<div>" + data.code + "</div>");
                    $("td:eq(6)", row).html("<div>" + data.consoleType + "</div>");

                    // Custom add more pro
                    // TODO
                    row.ondblclick = function () {

                        $state.go("adminTeamProfile", {company_id: session.getUser().company_id, id: data.team_id});
                        $scope.$apply();
                    };
                },
                "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.selectedItems = array;

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

                    // Using compile service
                    $compile(s.nTBody)($scope);
                },
                "columns": [
                    {"data": "team_id"},
                    {"data": "name"},
                    {"data": "mailAddress"},
                    {"data": "createdDate"},
                    {"data": "status"},
                    {"data": "code"},
                    {"data": "consoleType"}
                ],
                "columnDefs": [
                    {'orderable': false, 'targets': [0]}
                ]
            };

            $scope.removeTab = function () {
                localStorage.removeItem("tabs");
            };

            // Show confirm remove
            $scope.confirmDelete = function () {

                // Show modal
                AppUtil.confirm({
                    title: util.translate("message.team.title"),
                    message: util.translate("message.team.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
                            doDeleteTeam();
                            dialog.close();
                        }
                    }]
                });
            };

            // Do delete
            function doDeleteTeam() {

                var items = $scope.selectedItems;

                if (items.length === 0)
                    return;

                angular.forEach(items, function (item) {

                    var objUrl = {
                        method: APIName.TEAM_STATUS.method,
                        name: APIName.TEAM_STATUS.name + item + APIName.TEAM_STATUS.surfix + 2
                    };

                    AppUtil.createRequest(objUrl, null, function () {

                        $scope.table.draw();
                        // Reset selectedItems
                        $scope.selectedItems = [];

                    }, function (error) {
                        // Close toast
                        AppUtil.closeToast();
                        // Clean
                        $scope.selectedItems = [];
                    });
                });
                AppUtil.createToast({
                    text: util.translate("default_toast.deactivate_success"),
                    'type': 'success'
                });
            }

            $scope.exportTeam = function () {
                $http({
                    method: APIName.EXPORT_TEAM.method,
                    url: configServer.BACKEND_API_URL + APIName.EXPORT_TEAM.name + "?company_id=" + session.getUser().company_id,
                    headers: {
                        'auth-token': $scope.sessionToken
                    }
                }).success(function (res) {
                    var data = new Blob([res], {type: 'text/plain;charset=utf-8'});
                    FileSaver.saveAs(data, 'TeamList-' + new Date().getTime() + ".csv");

                })
            }
        }]);
