"use strict";

appCore.controller("MyDiaryAddCtrlClone", ["$state", "$scope", "$http", "$timeout", "vServices", "filterFilter", function ($state, $scope, $http, $timeout, vServices, filterFilter) {
    $scope.$root.page.title = "My Diary Entry";
    $scope.createButton = { heading: "Add", text: "Save All", icon: "fa-save", today: new Date() };
    let dupHandler = [];
    $scope.workingDates = [];
    $scope.leavesDates = [];
    $scope.restrictLeaves = [];
    $scope.halfDaysDates = [];
    $scope.heroId = $scope.$root.gUser.id;

    $scope.monthEnd = moment().endOf('month').format("DD-MM-YYYY");
    let dummyEntry = { proj_id: "", emp_id: $scope.$root.gUser.id, date: null, reference: "", description: "", logtype: "0", hours: 0, comments: "", diarytz: $scope.$root.gUser.workingtz ? $scope.$root.gUser.workingtz : 'Asia/Kolkata' };
    const getDummyEntry = (id, lastLockedDate) => {
        let d = JSON.parse(JSON.stringify(dummyEntry));
        d.proj_id = id;
        var today = new Date();
        var dd = today.getDate();
        var mm = today.getMonth() + 1; //January is 0!

        var yyyy = today.getFullYear();
        if (dd < 10) {
            dd = '0' + dd;
        }
        if (mm < 10) {
            mm = '0' + mm;
        }
        if (lastLockedDate) {
            d.lastLockedDate = moment(lastLockedDate).format("DD-MM-YYYY");
            d.lastLockedDate = moment(d.lastLockedDate, 'DD-MM-YYYY').add(1, 'days');
            d.lastLockedDate = d.lastLockedDate.format("DD-MM-YYYY");
        }
        else {
            d.lastLockedDate = '01-01-2020';
        }
        console.info(d.lastLockedDate)
        d.date = dd + '-' + mm + '-' + yyyy;
        d.logtype = '7';
        return d;
    };

    const onlyUnique = (value, index, array) => {
        return array.indexOf(value) === index;
    }

    $scope.changeCat = (pIdx, rowIdx) => {
        var logtype = $scope.diaries[pIdx].data[rowIdx].logtype;
        if (logtype == '16' || logtype == '17' || logtype == '22' || logtype == '23')
            $scope.diaries[pIdx].data[rowIdx].hours = 0;
    }

    $scope.diaries = [];

    $scope.addMore = (i, diary) => {
        $scope.diaries[i].data.push(getDummyEntry(diary.projectid, diary.proj_mydiaryLockDate));
    }
    $scope.removeSelf = (pIdx, rowIdx) => $scope.diaries[pIdx].data.splice(rowIdx, 1);

    const emptyHandler = (dataResult) => {
        let finalResult = [];
        return new Promise((resolve, reject) => {
            if (dataResult.length === 0) {
                reject(false)
            }
            for (let j = 0; j < dataResult.length; j++) {
                var data = dataResult[j];
                for (let i = 0; i < data.length; i++) {
                    let v = data[i];
                    if (v.date && v.hours >= 0 && v.description) {
                        finalResult.push(v);
                    }
                    if ((v.hours > 0 && !v.description) || (v.hours < 0 && v.description)) {
                        toastr.error("Sorry, there seems to be some issue in your filled data, kindly re-check the data and/or required fields.");
                        reject(false);
                        return;
                    }
                    if (i === data.length - 1 && j === dataResult.length - 1) {
                        // finalResult.length < 1 ? toastr.error("No Data to Save!") : toastr.success('Success! Added ' + finalResult.length + ' records for MyDiary.');
                        finalResult.length > 0 ? resolve(finalResult) : reject(false);
                    }
                }
            }
        });
    };

    const twoDto1D = (array) => {
        var temp = [];
        for (let i = 0; i < array.length; i++) {
            temp = temp.concat(array[i]);
        }
        return temp;
    }

    const myDiaryValidation = (data) => {
        console.log($scope.diaries);
        let tempArr = [];
        var leaves = ['16', '17', '22', '23'];
        var halfDay = ['24'];
        var allLeaves = $scope.leavesDates.map(x => x.date);
        var allLeavesOnlyServer = $scope.leavesDates.map(x => x.date);
        var allWorking = $scope.workingDates.map(x => x.date);
        var allHalfDays = $scope.halfDaysDates.map(x => x.date);
        var allHalfDaysOnlyServer = $scope.halfDaysDates.map(x => x.date);
        var twoDDatesWorking = $scope.diaries.map(x => x.data.filter(f => !leaves.includes(f.logtype) && !halfDay.includes(f.logtype)).map(o => o.date));
        var twoDDatesLeaves = $scope.diaries.map(x => x.data.filter(f => leaves.includes(f.logtype)).map(o => o.date));
        var twoDDatesHalfDay = $scope.diaries.map(x => x.data.filter(f => halfDay.includes(f.logtype)).map(o => o.date));
        var temArrWorking1 = twoDto1D(twoDDatesWorking);
        var temArrLeaves1 = twoDto1D(twoDDatesLeaves);
        var temArrHalfDay1 = twoDto1D(twoDDatesHalfDay);
        var temArrWorking = [];
        var temArrLeaves = [];
        var temArrHalfDay = [];
        for (let j = 0; j < temArrWorking1.length; j++) {
            temArrWorking.push(moment(temArrWorking1[j], 'DD-MM-YYYY').format('YYYY-MM-DD'));
        }
        for (let j = 0; j < temArrLeaves1.length; j++) {
            temArrLeaves.push(moment(temArrLeaves1[j], 'DD-MM-YYYY').format('YYYY-MM-DD'));
        }
        for (let j = 0; j < temArrHalfDay1.length; j++) {
            temArrHalfDay.push(moment(temArrHalfDay1[j], 'DD-MM-YYYY').format('YYYY-MM-DD'));
        }
        // var leavesFromDates = temArrLeaves.filter(onlyUnique);
        // var workingDates = temArrWorking.filter(onlyUnique);
        // var halfDays = temArrHalfDay.filter(onlyUnique);
        var leavesFromDates = temArrLeaves;
        var workingDates = temArrWorking;
        var halfDays = temArrHalfDay;
        for (let k = 0; k < leavesFromDates.length; k++) {
            allLeaves.push(leavesFromDates[k]);
        }
        for (let k = 0; k < workingDates.length; k++) {
            allWorking.push(workingDates[k]);
        }
        for (let k = 0; k < halfDays.length; k++) {
            allHalfDays.push(halfDays[k]);
        }
        return new Promise((resolve, reject) => {
            if (data.length === 0) {
                reject(false)
            }
            data.forEach((i, index) => {
                var cDate = moment(i.date, 'DD-MM-YYYY').format('YYYY-MM-DD');
                var logType = i.logtype.toString();
                var hours = i.hours ? parseFloat(i.hours) : 0;
                if (halfDay.includes(logType)) {
                    // var len = allHalfDays.filter(x=> x == cDate).length;
                    if (!allWorking.includes(cDate) && !allLeaves.includes(cDate) && !allHalfDaysOnlyServer.includes(cDate) && hours <= 4) {
                        tempArr.push(i);
                    } else {
                        toastr.error('Day already saved as working or leave, hours cannot be greater than 4. ' + cDate);
                        reject(false);
                        return;
                    }
                }
                if (leaves.includes(logType)) {
                    // var len = allLeaves.filter(x=> x == cDate).length;
                    if (!allWorking.includes(cDate) && !allHalfDays.includes(cDate) && !allLeavesOnlyServer.includes(cDate)) {
                        tempArr.push(i);
                    } else {
                        toastr.error('Day is already selected or saved. ' + cDate);
                        reject(false);
                        return;
                    }
                }
                if (!leaves.includes(logType) && !halfDay.includes(logType)) {
                    if (!allHalfDays.includes(cDate) && !allLeaves.includes(cDate)) {
                        tempArr.push(i);
                    } else {
                        toastr.error('Day already saved as leave or half day. ' + cDate);
                        reject(false);
                        return;
                    }
                }

                if (index === data.length - 1) {
                    tempArr.length > 0 ? resolve(tempArr) : reject(false);
                }
            })
        })
    }

    $scope.Save = () => {
        let dataResult = $scope.diaries.map((o) => o.data);
        emptyHandler(dataResult).then((data) => {
            if (data) {
                myDiaryValidation(data).then((result) => {
                    result.forEach(_myDiary => {
                        _myDiary.date = $scope.$root.convertDate2DateTimeUTC(_myDiary.date);
                    });
                    vServices.callApi("mydiary/add", "POST", { myval: JSON.stringify(data) }).then((res) => {
                        if (res) {
                            if (res.status == 'error') {
                                toastr.error(res.msg, "Error");
                            }
                            if (res.status == 'success') {
                                toastr.success(res.msg, "Message");
                                $state.go("myDiaryList", {}, { reload: true });
                            }
                        }
                    });
                })
            }
        }, (e) => {
            console.log(e);
        });
    };

    const createDiary = (res, cb) => {
        if (res) {
            res.map(o => {
                if (dupHandler.indexOf(o.projectid) === -1 && o.proj_status === 'active') {
                    dupHandler.push(o.projectid);
                    $scope.diaries.push({ projectid: o.projectid, proj_name: o.proj_name, last_filled_date: o.lastFilledDate, data: [getDummyEntry(o.projectid, o.proj_mydiaryLockDate)] });
                }
            });
            if (cb) {
                cb();
            }
        }
        else if (cb) {
            cb();
        }
    };
    const init = () => {
        console.log('ee', $scope.$root.gUser);
        $scope.diaries = [];
        let dupHandler = [];
        vServices.callApi("allocation/listbyempid/" + $scope.$root.gUser.id, "GET", {}).then((res1) => createDiary(res1, () => {
            // vServices.callApi("project/manager/" + $scope.$root.gUser.id, "GET", {}).then((res2) => createDiary(res2));
        }));
        vServices.callApi("mydiary/all_logtypes", "GET", {}).then((res) => {
            if (res) {
                $scope.logTypes = res;
                // $scope.logTypes.unshift({mydiarylogtypeid: "0", lt_name: "Select", lt_description: "", lt_status: "active"});
            }
        });


        const currentMonthLastDate = moment().clone().endOf('month').format('DD-MM-YYYY');
        const sixMonthsBack = moment().subtract(24, 'months').format('DD-MM-YYYY');
        vServices.callApi("mydiary/dataForCurrentDate?fromDate=" + sixMonthsBack + '&toDate=' + currentMonthLastDate, "GET", {}).then((res) => {
            if (res)
                $scope.leavesDates = res.leaveDays;
            $scope.workingDates = res.workingDays;
            $scope.halfDaysDates = res.halfDays;
            var highlight_dates = res.leaveDays.map(x => x.date);
            $scope.restrictLeaves = highlight_dates;
        });
    };
    if ($scope.$root.gUser.id > 1) {
        init();
    }
}]);
