"use strict";

appCore.controller("HeroListCtrl", ["$state", "$scope", "$http", "$timeout", "vServices", "$uibModal", "$document",
    function ($state, $scope, $http, $timeout, vServices, $uibModal, $document) {
        $scope.heroes = [];
        $scope.$root.page.title = "List of Heroes";
        $scope.dTable = null;
        $scope.inactiveHeroes = [];
        $scope.countryList=[];
        $scope.heroesList=[];
        $scope.selectCountry='0';
        $scope.isAllowImporter = $scope.$root.gUser.emp_acls.includes(",100,");
        $scope.isAdmin = $scope.$root.gUser.emp_acls.includes(",27,");

      $scope.colOptions = {department: false, designation: false, skills: false};

        $scope.notInPool = (h) => toastr.error(h.emp_first_name + " " + h.emp_last_name + " is fully allocated in other project(s)!", "Not Available", {timeOut: 5000});
        $scope.poolStatus = (level) => level > 50 ? "badge-danger" : level > 20 ? "badge-warning" : "badge-success";

        $scope.resetPassword = function (hero) {
            vServices.callApi("auth/forgot_password", "POST", {emp_email: hero.emp_email}).then(function (res) {
                if (res) {
                    toastr.success(res, "success", {timeOut: 5000});
                }
            });
        };

        $scope.allInactiveEmployees = function () {
            if($scope.dTable)$scope.dTable.destroy();
            vServices.callApi("employee/getAllInactiveEmployee", "GET").then(function (res) {
                if (res && res.length > 0) {
                    res.sort((a, b) => {
                        let prop = "emp_code";
                        return a[prop] > b[prop] ? 1 : a[prop] < b[prop] ? -1 : 0;
                    });
                    $scope.inactiveHeroes = res;
                    $scope.$root.callDataTable(".inactiveHeroes", 500, (t) => {
                        $scope.dTable = t;
                    }, {orientation: "landscape"});
                }
            });
        };

        $scope.allActiveEmployees = function () {
           init();
        };

        $scope.loginAs = function (heroid) {
            vServices.callApi("auth/login_as", "POST", {emp_id: heroid}).then(function (res, err) {
                if (res && res.status) {
                    if (localStorage.getItem("id_token")) {
                        localStorage.removeItem("id_token");
                        localStorage.setItem("id_token", res.token);
                        $scope.$root.mainLeft = $scope.$root.isAuthenticated = true;
                        $scope.$root.updateMenu();
                        $state.go("dashboard", {}, {});
                    }
                }
                else if (err) {
                    alert(err);
                }
            });
        };
        const init = function () {
            $scope.isActiveHeroes = true;
            $scope.myHeroes = [];
            if($scope.dTable)$scope.dTable.destroy();
            var certifiesHeroes = [];
            vServices.callApi("employee/IsHeroCertified", "GET", {}).then(function (getRes) {
                certifiesHeroes = getRes;
            });
            vServices.callApi("employee/all", "GET", {}).then(function (res) {
                if (res && res.length > 0) {

                    res.sort((a, b) => {
                        let prop = "emp_code";
                        return a[prop] > b[prop] ? 1 : a[prop] < b[prop] ? -1 : 0;
                    });
                    res.forEach((o)=>{
                        o.cert_hero_id = certifiesHeroes.includes(o.employeeid) ? '1' : '0';
                        o.emp_last_login = o.emp_last_login ? new Date(moment(o.emp_last_login)) : '';
                    });
                    $scope.heroesList = res;
                    $scope.heroes = $scope.heroesList;
                    $scope.$root.callDataTable(".heroList", 500, (t) => {
                        $scope.dTable = t;
                    }, {orientation: "landscape"});
                }
            });

            // Get all country 
            vServices.callApi("commonfunc/getCountriesList", "GET", {}).then(function (res) {
                if (res && res.length > 0) $scope.countryList = res;
            });
            $scope.allInactiveEmployees();
        };
        init();

        $scope.filterToCountry= function(val) {
            if($scope.dTable)$scope.dTable.destroy();
            if (val!='0') {
                let heroList= $scope.heroesList.filter(emp => emp.emp_country == val);  
                $scope.heroes=heroList;
                $scope.$root.callDataTable(".heroList", 500, (t) => {
                    $scope.dTable = t;
                }, {orientation: "landscape"});
            }else{
                $scope.heroes=$scope.heroesList;
                $scope.$root.callDataTable(".heroList", 500, (t) => {
                    $scope.dTable = t;
                }, {orientation: "landscape"});
            }
        }

        $scope.deleteHero = (employeeid) => {
            vServices.callApi("employee/delete/" + employeeid, "DELETE", {}).then((res) => {
                toastr.success(res, "Success");
                $state.go($state.current, {}, {reload: true});
            });
        };
        /* Model code start*/
        $scope.openHeroLeaveModel = (obj) => {
            vServices.callApi("allocation/allocationByHero?emp_id=" + obj.employeeid, "GET", {}).then(function (projects) {
                let modalInstance = $uibModal.open({
                    animation: true,
                    ariaLabelledBy: "modal-title",
                    ariaDescribedBy: "modal-body",
                    templateUrl: "HeroLeave.html",
                    controller: "HeroLeaveCtrl",
                    controllerAs: "$scope",
                    size: "md",//sm md lg
                    backdrop: "static",
                    resolve: {
                        data: () => {
                            return {
                                hero: obj,
                                projects: projects
                            };
                        }
                    }
                });
                modalInstance.result.then((data) => {
                    $scope.deleteHero(data);
                }, () => {
                    toastr.warning("Action has been canceled", "Cancel");
                });
            });
        };
        /* Model code end*/

    }]).controller("HeroLeaveCtrl", function ($uibModalInstance, data, $scope,vServices) {
        $scope.data = data;
        $scope.heroProjects = 0;
        if($scope.data.projects != null){
            $scope.heroProjects = $scope.data.projects;
        }
        $scope.heroHistory = {hero_id : data.hero.employeeid, release_type : '',lm_comment : '',last_date : moment().format('YYYY-MM-DD')};
        $scope.removeHero = () =>{
            if($scope.heroHistory.release_type==""){
                toastr.error("Please select removing type", "Cannot Empty");
            }
            else if($scope.heroHistory.lm_comment==""){
                toastr.error("Please type some comment for hero", "Cannot Empty");
            }
            else if($scope.heroHistory.last_date > moment().format('YYYY-MM-DD')){
                toastr.error("Cannot choose future date", "Last date of hero's tenure");
            }
            else if($scope.heroHistory.last_date <= moment().format('YYYY-MM-DD') && $scope.heroHistory.lm_comment!="" && $scope.heroHistory.release_type!=""){
                console.log(data);
                vServices.callApi("employee/removeHero","POST", { 'heroData' : JSON.stringify($scope.heroHistory),'projects' : JSON.stringify($scope.heroProjects)}).then((res) => {
                    if(res){
                        $uibModalInstance.close(data.hero.employeeid);
                    }
                });
            }
        }
        $scope.cancel = () => $uibModalInstance.dismiss("cancel");
});
