"use strict";
appCore.controller("MyDiaryListCtrl", ["$state", "$scope", "$http", "$timeout", "vServices", "$uibModal", "$document", function ($state, $scope, $http, $timeout, vServices, $uibModal, $document) {
    $scope.$root.page.title = "My Diary";
    $scope.myDiary = [];
    $scope.filter = {
        fromDate: moment().subtract(2, "weeks").format("DD-MM-YYYY"),
        toDate: moment().add(1, "day").format("DD-MM-YYYY")
    };
    $scope.oldDate = '';

    const convertDataToDisplay = res => {
        $scope.myDiary = null;
        if (res && res.length > 0) {
            $scope.myDiary = [];
            let newResult = res.map(o => o.proj_name + "~" + o.proj_id).filter((v, i, s) => s.indexOf(v) === i).sort();
            res.forEach(element => {
                //element.dateUtc  = moment.utc(element.date).format('ll');
                // element.dateUtc  = moment.utc(element.date).utcOffset(moment().utcOffset()).format('ll')
                element.dateUtc = moment(element.date).format("ll");
            });
            console.log(res);
            for (let i = 0; i < newResult.length; i++) {
                const o = newResult[i];
                const proj = o.split("~");
                $scope.myDiary.push({proj_name: proj[0], proj_id: proj[1], data: res.filter(j => j.proj_id === proj[1])});
                if (i === newResult.length - 1) {
                    $scope.$root.callDataTable(".myDiaryList", 1000, (t) => {
                        try {
                            $scope.dTable = t;
                            //t.columns(6).data().flatten().filter(function (value, index) {return value === 1;});
                            //t.column(6).search(0).draw();
                            //$scope.dTable.column(6).search('^(?![,.0]*$)\\d{1,4}(?:[.,]\\d{1,2})?$', true, false).draw();
                            // $scope.viewConditionsHandler();
                        }
                        catch (e) {
                            console.error(e);
                        }
                    });
                }
            }
        }
        else {
            toastr.info('', "No data found");
        }
    };
    $scope.repeatDiaryCurrentWeek = (diaryObj) => {
        vServices.callApi("mydiary/repeat_diary_current_week", "PUT", diaryObj).then(function (res) {
            if (res) {
                toastr.success(res, "Success");
                $state.go($state.current, {}, {reload: true});
            }
        });
    }
    /* Model code start*/
    $scope.openMyDiaryDeleteModal = (obj) => {
        let modalInstance = $uibModal.open({
            animation: true,
            ariaLabelledBy: "modal-title",
            ariaDescribedBy: "modal-body",
            templateUrl: "MyDiaryDelete.html",
            controller: "MyDiaryDeleteCtrl",
            controllerAs: "$scope",
            size: "md",//sm md lg
            backdrop: "static",
            resolve: {
                data: obj
            }
        });
        modalInstance.result.then((data) => {
            $scope.deleteMyDiary(data);
        }, () => {
            toastr.warning("Action has been canceled", "Cancel");
        });
    };
    /* Model code end*/
    $scope.deleteMyDiary = (e) => {
        console.log(e);
        vServices.callApi("mydiary/delete/" + e.mydiaryid, "DELETE", {}).then((res) => {
            toastr.success(res, "Success");
            $state.go($state.current, {}, {reload: true});
        });
    };

    $scope.dateChanged = (first = false) => {
        if (!first) {
            if (!$scope.filter.fromDate) {
                toastr.error("Please provide valid FromDate");
            }
            else if (!$scope.filter.toDate) {
                toastr.error("Please provide valid toDate");
            }
            else {
                const _fromDate = $scope.$root.convertDate2DateTimeUTC($scope.filter.fromDate, 'DD-MM-YYYY','00:00:00');
                const _toDate = $scope.$root.convertDate2DateTimeUTC($scope.filter.toDate, 'DD-MM-YYYY','23:59:59');
                const url = `mydiary/me?fromDate=${encodeURIComponent(_fromDate)}&toDate=${encodeURIComponent(_toDate)}`;
                vServices.callApi(url, "GET", {}).then(res => res ? convertDataToDisplay(res) : false);
            }
        }
    }
    const init = () => $scope.dateChanged();
    init();

    /* Model code start 9899222772 */
    $scope.openEditMyDiaryEntry = (obj) => {
        let modalInstance = $uibModal.open({
            animation: true,
            ariaLabelledBy: "modal-title",
            ariaDescribedBy: "modal-body",
            templateUrl: "EditMyDiaryEntry.html",
            controller: "EditMyDiaryEntryCtrl1",
            controllerAs: "$scope",
            size: "md",//sm md lg
            backdrop: "static",
            resolve: {
                data: () => {
                    return {diary: obj,};
                }
            }
        });
        modalInstance.result.then((data) => {
        }, () => {
            toastr.warning("Action has been canceled", "Cancel");
        });
    };
    /* Model code end*/

}]);
appCore.controller("EditMyDiaryEntryCtrl1", function ($state, $uibModalInstance, data, $scope, vServices) {
    $scope.data = data;
    console.log($scope.data);

    if ($scope.data.diary.date && $scope.data.diary.date.match(/^(0?[1-9]|[12][0-9]|3[01])[\/\-](0?[1-9]|1[012])[\/\-]\d{4}$/)) {
        $scope.data.diary.date = $scope.data.diary.date;
        $scope.oldDate = $scope.data.diary.date;
    }
    else {
        // If date format is not DD-MM-YYYY then parse it to moment format and convert it to DD-MM-YYYY
        $scope.data.diary.date = moment($scope.data.diary.date).format('DD-MM-YYYY');
        $scope.oldDate = $scope.data.diary.date;
    }

    vServices.callApi("mydiary/all_logtypes", "GET", {}).then((res) => {
        if (res) {
            $scope.logTypes = res;
            // $scope.logTypes.unshift({"mydiarylogtypeid": 0, "lt_name": "Select", "lt_description": ""});
        }
    });

    $scope.change = (d) => {
        if ($scope.data.diary.date && $scope.data.diary.hours && $scope.data.diary.description) {
            console.log($scope.data.diary.date)
            $scope.data.diary.date = $scope.convertDate2DateTimeUTC($scope.data.diary.date, 'DD-MM-YYYY');
            $scope.data.diary.old_date = $scope.convertDate2DateTimeUTC($scope.oldDate, 'DD-MM-YYYY');
            vServices.callApi("mydiary/edit", "PUT", $scope.data.diary).then(function (res) {
                if (res) {
                    toastr.success(res, "Success");
                    $uibModalInstance.close(true);
                    $state.go($state.current, {}, {reload: true});
                }
            });
        }
        else {
            toastr.error("Please provide values for all required fields (marked with *)");
        }

    };
    $scope.cancel = () => $uibModalInstance.dismiss("cancel");

    $scope.convertDate2DateTimeUTC = (_date = moment().format('DD-MM-YYYY'), _format = 'DD-MM-YYYY') => {
        /**
         * Get user system date in DD-MM-YYYY format
         */
        let user_date, user_time, user_date_time, user_date_time_utc;
        user_date = moment(_date, _format).format('DD-MM-YYYY');
        /**
         * Get user system time in 24 hours format HH:mm:ss
         */
        user_time = moment().format('HH:mm:ss');

        /***
         * Concat date and time in DD-MM-YYYY HH:mm:ss format
         */
        user_date_time = user_date + ' ' + user_time;
        /***
         * Add UTC time zone in DD-MM-YYYY HH:mm:ss ZZ format
         */
        user_date_time_utc = moment(user_date_time, 'DD-MM-YYYY HH:mm:ss').format('DD-MM-YYYY HH:mm:ss ZZ');
        return user_date_time_utc;
    };


});
appCore.controller("MyDiaryDeleteCtrl", function ($uibModalInstance, data, $scope) {
    $scope.data = data;

    $scope.delMyDiary = (d) => $uibModalInstance.close(d);
    $scope.cancel = () => $uibModalInstance.dismiss("cancel");
});

