"use strict";

appCore.controller("MyDiaryAddCtrl2", ["$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.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: ""};
    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;
    };

    $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);
                    }
                }
            }
        });
    };

    $scope.Save = () => {
        let dataResult = $scope.diaries.map((o) => o.data);
        emptyHandler(dataResult).then((data) => {
            if (data) {
                data.forEach(a=>{
                    a.date = moment(a.date+moment().format('HH:mm:ss'),'DD-MM-YYYY HH:mm:ss').format('YYYY-MM-DD HH:mm:ss ZZ');
                });
                console.log(data);
                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 = () => {
        $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"});
            }
        });
    };
    if ($scope.$root.gUser.id > 1)
        init();
}]);
