"use strict";
appCore.controller("ProjectTimelineCtrl", ["$state", "$scope", "$http", "$timeout", "vServices", "filterFilter", "$rootScope",
    function ($state, $scope, $http, $timeout, vServices, filterFilter, $rootScope) {
        $scope.param = {proj_id: null};
        $scope.nodata = "";
        $scope.projects = [];
        $scope.gColumnChart = null;
        $scope.projectsData = [];
        $scope.tempProjectsData = [];
        $scope.currentIndex = 0;
        $scope.viewProject = (action) => $scope.param.proj_id = $scope.projects[($scope.currentIndex + (action === 'next' ? 1 : -1))].projectid;

        const checkForDateDiff = (d1, d2) => moment(d1).diff(moment(d2), 'days');
        // Get project list
        vServices.callApi("project/all", "GET", {}).then(res => {
            if (res) {
                res = $scope.$root.sort(res, 'proj_name');
                $scope.projects = res;
            }
        });
        const getFormatDate = (d) => {
            try {
                return moment(moment(d).format('YYYY-MM-DD').toString()).toDate();
            } catch (e) {
                console.error(d);
                return new Date();
            }
        };
        var renderGraph = (projData) => {
            // google.charts.load('current', {'packages': ['line']});
            google.charts.load("current", {packages: ['corechart']});
            google.charts.setOnLoadCallback(drawChart);

            function drawChart() {
                var data = google.visualization.arrayToDataTable(projData);
                var container = document.querySelector('#projectTimelineGraph');
                var options = {
                    //title: "Project Allocation Graph Month-wise",
                    colors: ['#33ac71', '#ff8679'],
                    width: container.clientWidth ? container.clientWidth - 10 : 1000,
                    height: 400,
                    chartArea: {width: '94%', height: '75%', borderRadius: '10px'},
                    legend: {position: 'top', maxLines: 1},
                    bar: {groupWidth: '90%'},
                    isStacked: true,
                    vAxis: {minValue: 0},
                    hAxis: {
                        textStyle: {
                            fontSize: 12 // or the number you want
                        },
                        title: 'Months',
                        //slantedText:true,
                        //slantedTextAngle:10
                    }
                };
                var view = new google.visualization.DataView(data);
                view.setColumns([0, 1, {calc: "stringify", sourceColumn: 1, type: "string", role: "annotation"}, 2, {calc: "stringify", sourceColumn: 2, type: "string", role: "annotation"}]);
                //view.setColumns([1, 1, {calc: "stringify", sourceColumn: 2, type: "string", role: "annotation"}, 2]);

                $scope.gColumnChart = new google.visualization.ColumnChart(container);
                $scope.gColumnChart.draw(view, options);
            }

            function drawChart1() {
                var data = new google.visualization.DataTable();
                data.addColumn('date', 'Months');
                data.addColumn('number', 'Billable User');
                data.addColumn('number', 'Total Users');
                data.addRows(projData);
                var container = document.querySelector('#projectTimelineGraph');
                var options = {
                    chart: {
                        title: 'Project Timeline Graph',
                        subtitle: ''
                    },
                    width: container.clientWidth,
                    height: 500,
                    axes: {
                        x: {
                            0: {side: 'bottom'}
                        }
                    }
                };
                var chart = new google.charts.Line(container);
                chart.draw(data, google.charts.Line.convertOptions(options));
            }
        };
        const dataHandler = (res) => {
            if (res && res.length > 0) {
                var temp = {dup: [], data: [], tempGraph: [], graph: []};

                // formating data
                res.map((o) => {
                    o.fromDate = moment(o.fromDate);
                    o.toDate = moment(o.toDate);
                    o['isSame'] = checkForDateDiff(o.toDate, o.fromDate) < 2;
                    o['months'] = moment(o.toDate).format('MMYYYY')
                });

                res = $scope.$root.sort(res, 'employeeid');
                res = $scope.$root.sort(res, 'createdAt', 'date', 'asc');
                res.forEach((o) => {
                    var toCheck = moment(o.fromDate).format('MMYYYY') + '#' + o.employeeid;
                    // console.log(toCheck);
                    if (temp.dup.indexOf(toCheck) === -1) {
                        temp.dup.push(toCheck);
                        o['char'] = o.emp_first_name.substring(0, 1).toUpperCase();
                        temp.data.push(o);
                    }
                });
                temp.data = $scope.$root.sort(temp.data, 'employeeid');
                // console.log(temp.data)
                //temp.data = $scope.$root.sort(temp.data, 'createdAt', 'date', 'asc');
                var today = {year: moment().format('YYYY'), month: moment().format('MM'), day: moment().format('DD')};
                var years = [parseInt(moment().format('YYYY')), moment().format('YYYY') -1];
                var months = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'];
                $scope.tempProjectsData = [['Month', 'Billable', 'Non-Billable', {role: 'annotation'}]];
                var continueLoop = true;
                var projectsData = [];
                for (var i = 0; (i < years.length); i++) {
                    for (var j = 0; (j < months.length && continueLoop); j++) {
                        var year = years[i], month = months[j],
                            startOfMonth = moment(year + month, "YYYYMM").startOf('month'),
                            endOfMonth = moment(year + month, "YYYYMM").endOf('month');

                        // get before current month data
                        var active = temp.data.filter((o) => o.status === 'active' && moment(o.fromDate) <= startOfMonth);
                        // get current month data
                        var activeCurrentMonth = temp.data.filter((o) => o.status === 'active' && moment(o.fromDate) > startOfMonth && moment(o.fromDate) <= endOfMonth);
                        active = active.concat(activeCurrentMonth);

                        // get before current month data
                        var inactive = temp.data.filter((o) => o.status === 'inactive' && moment(o.fromDate) <= startOfMonth && moment(o.toDate) >= startOfMonth);
                        // get current month data
                        var inactiveCurrentMonth = temp.data.filter((o) => o.status === 'inactive' && moment(o.fromDate) > startOfMonth && moment(o.fromDate) <= endOfMonth);
                        inactive = inactive.concat(inactiveCurrentMonth);

                        // remove duplicate if any
                        var inactiveDup = [], activeDup = [], totalDup = [], totalCount = 0, billable = 0;
                        active = active.length > 0 ? active.filter(o => activeDup.indexOf(o.emp_id) === -1 ? activeDup.push(o.emp_id) || true : false) : [];
                        inactive = inactive.length > 0 ? inactive.filter(o => inactiveDup.indexOf(o.emp_id) === -1 ? inactiveDup.push(o.emp_id) || true : false) : [];

                        var total = active.length > 0 && inactive.length > 0 ? active.concat(inactive) : active.length > 0 ? active : inactive.length > 0 ? inactive : [];
                        total = total.length > 0 ? total.filter(o => totalDup.indexOf(o.emp_id) === -1 ? totalDup.push(o.emp_id) || true : false) : [];

                        // remove duplicate if any
                        if (total.length > 0) {
                            total = $scope.$root.sort(total, 'emp_first_name');
                            billable = total.filter((o) => o.billableHours > 0).length;
                            totalCount = total.length;
                            projectsData = [{from: startOfMonth.toDate(), to: endOfMonth.toDate(), char: startOfMonth.format('MMM').substring(0, 1).toUpperCase(), new: true}].concat(total).concat(projectsData);
                        }

                        if (billable > -1 && totalCount > 0) {
                            $scope.tempProjectsData.push(["(" + totalCount + ")" + startOfMonth.format('MMMYY'), billable, totalCount - billable, '']);
                        }

                        if ((i === years.length - 1 && j === months.length - 1) || (year == today.year && month == today.month)) {
                            $scope.projectsData = projectsData;
                            renderGraph($scope.tempProjectsData);
                            // continueLoop = false;
                            break;
                        }
                    }
                    if (!continueLoop) break;
                }
            } else {
                $scope.nodata = "No data available, Please try different project";
            }
        };
        const getDataOfProject = (projid) => vServices.callApi("project/project_loading_monthly/" + projid, "GET", {}).then(dataHandler);

        $scope.$watch("param.proj_id", (newValue, oldValue) => {
            //console.log(newValue);
            if (newValue && newValue !== oldValue) {
                $scope.nodata = "";
                $scope.projectsData = [];
                $scope.tempProjectsData = [];
                if ($scope.gColumnChart) $scope.gColumnChart.clearChart();
                getDataOfProject(newValue);
                $scope.currentIndex = $scope.projects.findIndex(o => o.projectid === newValue);
            }
        });
    }
])
;
