"use strict";

appCore.controller("HeroProjectTimelineCtrl", ["$state", "$scope", "$http", "$timeout", "vServices", "filterFilter", "$rootScope", function ($state, $scope, $http, $timeout, vServices, filterFilter, $rootScope) {
    $scope.param = $state.params;
    // $scope.param['employeeid'] = parseInt($scope.$root.gUser.id) > 1 ? parseInt($scope.$root.gUser.id) : 0;
    $scope.tempProjects = [];
    $scope.projectsearlier = [];
    $scope.projectsTimeline = [];
    $scope.projectsTimelineData = [];

    const init = () => vServices.callApi("employee/allForTimeline", "GET", {}).then(res => convertDataForProject(res));
    const convertDataForProject = res => {
        if (res) {
            $scope.employee = [];
            $scope.employee.push({id: 0, name: " Select or search a Hero"});
            // res = res.filter(emp => emp.emp_status === 'active');
            res.map((o) => $scope.employee.push({id: o.employeeid, name: o.emp_first_name + (o.emp_middle_name ? ' ' + o.emp_middle_name + ' ' : ' ') + o.emp_last_name + ' (' + o.emp_code + ')', emp_status: o.emp_status}));
            $scope.employee = $scope.$root.sort($scope.employee, 'name');
            console.log($scope.param.employeeid);
            $timeout(()=>init1($scope.param.employeeid),1000);
        }
    };
    const getFormatDate = (d) => {
        try {
            return moment(moment(d).format('YYYY-MM-DD').toString()).toDate();
        } catch (e) {
            console.error(d);
            return new Date();
        }
    };
    const isOngoing = (o, returnType) => {
        try {
            if (returnType === 'bool')
                return moment(o.fromDate).format('DDMMYYYY').toString() === moment(o.updatedAt).format('DDMMYYYY').toString();
            else
                return moment(o.fromDate).format('DDMMYYYY').toString() === moment(o.updatedAt).format('DDMMYYYY').toString() ? moment() : o.updatedAt;
        } catch (e) {
            console.info(o.fromDate + '\t' + o.updatedAt);
            console.error(e);
            return moment();
        }
    };
    const init2 = function () {
        var data = $scope.projectsTimelineData;

        //console.log(data);
        google.charts.load("current", {packages: ["timeline"]});
        google.charts.setOnLoadCallback(drawChart);

        function drawChart() {
            if (data && data.result && data.result.length > 0) {
                var container = document.querySelector('#projTimelineGraph');
                var chart = new google.visualization.Timeline(container);
                var dataTable = new google.visualization.DataTable();
                dataTable.addColumn({type: 'string', id: 'Project'});
                dataTable.addColumn({type: 'string', id: 'Account'});
                dataTable.addColumn({type: 'string', id: 'style', role: 'style'});
                dataTable.addColumn({type: 'date', id: 'Start'});
                dataTable.addColumn({type: 'date', id: 'End'});

                //data.result.forEach(o => dataTable.addRows(o));
                dataTable.addRows(data.result);
                var options = {
                    height: 40 * (data && data.totProject && data.totProject < 8 ? (data.totProject + 2) : 10),
                    'is3D': true,
                    width: container.clientWidth,
                    avoidOverlappingGridLines: false,
                    /*animation:{
                        duration: 1000,
                        easing: 'inAndOut',
                        startup: true
                    }*/
                };
                chart.draw(dataTable, options);

                /*$(window).resize(function() {
                    chart.clearChart();
                    chart.draw(dataTable, options);
                });*/
            }
        }
    };
    const checkForDateDiff = (l, o, diff) => {
        var a = moment(l[l.length - 1].updatedAt);
        var b = moment(o.updatedAt);
        var result = a.diff(b, 'days') >= diff;
        //console.log(l[l.length-1].updatedAt,o.updatedAt,result);
        return result;
    };
    const dataFormationForChart = () => {
        //console.log($scope.projectsTimeline);
        var temp = {
            dupProject: [],
            totProject: 0,
            data: [],
            result: []
        };
        temp.data = $scope.$root.sort($scope.projectsTimeline, 'updatedAt', 'date', 'desc');
        temp.data = $scope.$root.sort($scope.projectsTimeline, 'fromDate', 'date', 'asc');
        temp.data = $scope.$root.sort(temp.data, 'projectid');

        $scope.projectsTimeline = [];
        temp.data.filter(o => moment(o.fromDate) < moment(o.isOngoingValue)).forEach((o, i) => {
            //console.log(moment(o.fromDate) < moment(o.isOngoingValue));
            if (temp.dupProject.indexOf(o.projectid) === -1) {
                temp.totProject++;
                temp.dupProject.push(o.projectid);
            }
            if (i > 0 && $scope.projectsTimeline[i - 1].projectid === o.projectid && moment(o.fromDate) < moment($scope.projectsTimeline[i - 1].isOngoingValue)) {
                $scope.projectsTimeline[i - 1].isOngoingValue = o.fromDate;
            }
            $scope.projectsTimeline.push(o);
        });

        $scope.projectsTimeline.forEach((o) => {
            var colorCode = o.isBillable ? (parseInt(o.partialHours) === 8 ? '#00A65A' : '#00C0EF') : '#cccccc';
            temp.result.push([o.proj_name, o.acc_company_name, colorCode, getFormatDate(o.fromDate), getFormatDate(o.isOngoingValue)]);
        });
        $scope.projectsTimelineData = temp;
        init2();
    };
    const init1 = function (employeeid) {
        if (employeeid && employeeid > 1) {
            var url = "/allocation/getEarlierProjectByEmployeeOnActive/" + employeeid;
            vServices.callApi(url, "GET", {}).then((res) => {
                if (res) {
                    //check valid partial hours
                    res = res.filter(o => o.partialHours && !Number.isNaN(o.partialHours) && parseInt(o.partialHours) > -1);
                    //res = $scope.$root.sort(res, 'fromDate', 'date');
                    res = $scope.$root.sort(res, 'partialHours');
                    res = $scope.$root.sort(res, 'updatedAt', 'date','desc');
                    res = $scope.$root.sort(res, 'projectid', '');
                    const resWithLatestDate = res.filter(x=> x.projectid != 116).sort((a,b)=>{
                        return moment(b?.toDate||moment()) - moment(a?.toDate || moment());
                    });
                    //handle one week gap between two record
                    res.forEach((o, i) => {
                        if ($scope.tempProjects.length > 0 && o.partialHours && $scope.tempProjects[$scope.tempProjects.length - 1].projectid !== o.projectid) {
                            o['ok'] = 1 + '-' + i;
                            const latestDataOfProject = resWithLatestDate.filter(x=> x.projectid == o.projectid);
                            if(latestDataOfProject && latestDataOfProject.length > 0){
                                o.toDate = latestDataOfProject ? latestDataOfProject[0].toDate : o.fromDate;
                            }
                            $scope.tempProjects.push(o);
                        } else if ($scope.tempProjects.length > 0 && o.partialHours && checkForDateDiff($scope.tempProjects, o, 7) && $scope.tempProjects[$scope.tempProjects.length - 1].partialHours !== o.partialHours) {
                            o['ok'] = 2 + '-' + i;
                            $scope.tempProjects.push(o);
                        } else if ($scope.tempProjects.length > 0 && o.partialHours && !checkForDateDiff($scope.tempProjects, o, 7)) {
                            $scope.tempProjects[$scope.tempProjects.length - 1]['ok'] = 3 + '-' + i;
                            //console.log($scope.tempProjects[$scope.tempProjects.length - 1]['ok'],$scope.tempProjects[$scope.tempProjects.length - 1].updatedAt +"="+ o.updatedAt);
                            $scope.tempProjects[$scope.tempProjects.length - 1].updatedAt = o.updatedAt;
                        } else if ($scope.tempProjects.length === 0) {
                            o['ok'] = 9 + '-' + i;
                            $scope.tempProjects.push(o);
                        }
                    });
                    $scope.tempProjects = $scope.$root.sort($scope.tempProjects, 'fromDate', 'date');

                    var dupVal = [];
                    $scope.tempProjects.forEach((o, i) => {
                        o['char'] = o.proj_name.substring(0, 1).toUpperCase();
                        o['isOngoing'] = isOngoing(o, 'bool');
                        o['isOngoingValue'] = isOngoing(o, 'value');
                        if (dupVal.indexOf(o.fromDate) === -1) {
                            dupVal.push(o.fromDate);
                            o['new'] = true;

                            $scope.projectsearlier.push(o);

                            var o1 = JSON.parse(JSON.stringify(o));
                            o1['new'] = false;
                            $scope.projectsearlier.push(o1);
                            $scope.projectsTimeline.push(o1);
                        } else {
                            o['new'] = false;
                            $scope.projectsearlier.push(o);
                            $scope.projectsTimeline.push(o);
                        }
                    });
                    dataFormationForChart();
                }
            });
        }
    };
    $scope.$watch("param.employeeid", (newValue, oldValue) => {
        //console.log(newValue, oldValue);
        if (newValue && newValue !== oldValue && newValue > 1) {
            $scope.tempProjects = [];
            $scope.projectsearlier = [];
            $scope.projectsTimeline = [];
            $scope.projectsTimelineData = [];
            init1(newValue);
        }
    });
    init();
}]);
