"use strict";

appCore.controller("HeroViewCtrl", ["$state", "$scope", "$http", "$timeout", "vServices", "filterFilter",
    function ($state, $scope, $http, $timeout, vServices, filterFilter) {
        $scope.param = $state.params;
        $scope.hero = [];
        $scope.hero_tags = [];
        $scope.projects = [];
        $scope.projectsearlier = [];
        $scope.myHeroesProjects = [];
        $scope.managerView = [];
        $scope.filterData = {lm: true, pm: true};
        $scope.isSuperAdmin = $scope.$root.gUser.emp_acls.split(',').indexOf('27')>=0?'true':'false';
        $scope.isSystemUser = $scope.$root.gUser.emp_acls.split(',').indexOf('97')>=0?'true':'false';

        $scope.lmfilter = (o) => o.linemgr.employeeid === $scope.param.employeeid;
        $scope.pmfilter = (o) => o.projmgr.employeeid === $scope.param.employeeid;
        const isOngoing = (o, returnType) => {
            try {
                if (returnType === 'bool')
                    return moment(o.fromDate).format('DDMMYYYY').toString() === moment(o.toDate).format('DDMMYYYY').toString();
                else
                    return moment(o.fromDate).format('DDMMYYYY').toString() === moment(o.toDate).format('DDMMYYYY').toString() ? moment() : o.toDate;
            } catch (e) {
                console.info(o.fromDate + '\t' + o.toDate);
                console.error(e);
                return moment();
            }
        };
        const init = function () {
            
            if ($scope.param && typeof $scope.param.employeeid !== "undefined") {
                $scope.param.employeeid = parseInt($scope.param.employeeid);
                vServices.callApi("employee/" + $scope.param.employeeid, "GET", {}).then(function (res) {
                    if (res) $scope.hero = res;
                    $scope.$root.page.title = "Our Hero " + $scope.hero.emp_first_name + " " + $scope.hero.emp_last_name;
                    vServices.callApi("employee/get_tagged_employees/" + $scope.param.employeeid, "GET", {}).then(function (res) {
                        if (res) $scope.hero_tags = res;
                    });
                    vServices.callApi("allocation/listbyempid/" + $scope.param.employeeid, "GET", {}).then(function (res) {
                        if (res) {
                            $scope.projects = res.length > 0 ? res : [res];

                            let allTeam = [];
                            $scope.projects.forEach((o) => {
                                allTeam.push(new Promise((resolve, reject) => {
                                    const projInfo = {id: o.projectid, name: o.proj_name, cdate: o.proj_created_date,mngr:o.projmgr};
                                    vServices.callApi("allocation/list/" + o.projectid, "GET", {}).then(function (res) {
                                        if (res) {
                                            $scope.myHeroesProjects.push({proj: projInfo, data: res});
                                            $scope.managerView.push(...res);
                                        }
                                        resolve(res);
                                    });
                                }));
                            });
                            console.log($scope.projects);
                            Promise.all(allTeam).then(function (data) {
                                let templm = false, temppm = false;
                                for (let i = 0; i < $scope.managerView.length; i++) {
                                    const o = $scope.managerView[i];
                                    templm = templm || o.linemgr.employeeid === $scope.param.employeeid;
                                    temppm = temppm || o.projmgr.employeeid === $scope.param.employeeid;

                                    if (i === $scope.managerView.length - 1 && $scope.$root.callDataTable != null) {
                                        $scope.$root.callDataTable(".teamView", 2000);
                                        $scope.$root.callDataTable("#taggedheroes", 2000);
                                        $scope.$root.callDataTable("#projectManagerView", 500, (t) => {
                                            data = t.order([1, 'asc']).draw();
                                        });
                                        $scope.$root.callDataTable("#lineManagerView", 500, (t) => {
                                            data = t.order([1, 'asc']).draw();
                                        });
                                        $timeout(() => {
                                            $scope.filterData.lm = templm;
                                            $scope.filterData.pm = temppm;
                                        }, 800);
                                    }
                                }
                            });

                        }
                    });
                    vServices.callApi("allocation/listbyempidearlier/" + $scope.param.employeeid, "GET", {}).then(function (res) {
                        if (res) {
                            var temp = {
                                dup: [],
                                data: []
                            };
                            res = res.length > 0 ? res : [res];
                            res = $scope.$root.sort(res, 'projectid', '');
                            if (res.length === 1) {
                                temp.data = res;
                            } else {
                                const resWithLatestDate = res.sort((a,b)=>{
                                    return moment(b?.toDate||moment()) - moment(a?.toDate || moment());
                                })
                                res.forEach((o, i) => {
                                    //update Maximum allocation hours in project
                                    if (i > 0 && res[i - 1].projectid === o.projectid && ((Number.isNaN(res[i - 1].partialHours) && Number.isNaN(o.partialHours)) || res[i - 1].partialHours < o.partialHours)) {
                                        res[i - 1].partialHours = o.partialHours;
                                        res[i - 1]['isOngoing'] = isOngoing(o, 'bool');
                                        res[i - 1].updatedAt = isOngoing(o);
                                    }
                                    //distinct project
                                    if (temp.dup.indexOf(o.projectid) === -1) {
                                        temp.dup.push(o.projectid);
                                        o['isOngoing'] = isOngoing(o, 'bool');
                                        o.updatedAt = isOngoing(o);
                                        const latestDataOfProject = resWithLatestDate.filter(x=> x.projectid == o.projectid);
                                        if(latestDataOfProject && latestDataOfProject.length > 0){
                                            o.LatestDate = latestDataOfProject[0].toDate ? latestDataOfProject[0].toDate : o.fromDate;
                                        }
                                        temp.data.push(o);
                                    }
                                });
                            }
                            temp.data = $scope.$root.sort(temp.data, 'fromDate', 'date');
                            $scope.projectsearlier = temp.data;
                            console.log($scope.projectsearlier);
                            // $scope.projectsearlier = res;

                        }
                    });
                });
            } else {
                toastr.error("Invalid Id", "Error");
            }
            
        };
        init();
    }]);
