// -------------------------------
// Define REST models
//
archDB.factory('Reminder', ['apiUrl', '$resource', 'ResourceMethods', 'ResourcePrototype', function (apiUrl, $resource, methods, _prototype) {
    var Reminder = $resource(apiUrl('reminders/:reminderId'), { reminderId: '@id' }, methods);
    angular.extend(Reminder.prototype, _prototype);
    return Reminder;
}]);
archDB.controller('ReminderModalCtrl', ['$scope', '$AuthUser', 'DateTime', '$uibModalInstance', 'Reminder', 'ErrorsHandler', function ($scope, $AuthUser, DateTime, $uibModalInstance, Reminder, ErrorsHandler) {

    $scope.data = {
        user_id: $AuthUser.data.id,
    };

    $scope.selected_date = angular.copy(DateTime.defaults);
    $scope.selected_date.date = new Date();
    $scope.DateTime = DateTime;

    $scope.$watch('selected_date', function (value) {
        var date = moment(value.date);

        $scope.data.remind_at = moment({
            day: parseInt(date.format('DD'), 10),
            month: parseInt(date.format('MM'), 10) - 1,
            year: parseInt(date.format('YYYY'), 10),
            hour: parseInt(value.hours, 10),
            minute: parseInt(value.minutes, 10),
            second: 0
        }).format('YYYY-MM-DD HH:mm:ss');
    }, true);


    $scope.save = function () {
        Reminder.save($scope.data, function (response) {
            $uibModalInstance.close(response);
        }, ErrorsHandler);
    };

    $scope.cancel = function () {
        $uibModalInstance.dismiss('cancel');
    };

}]);
archDB.controller('RemindersCtrl', ['$scope', 'Reminder', 'ErrorsHandler', '$timeout', '$uibModal', '$DesktopNotification', '$AuthUser', 'ngAudio', '$interval', function ($scope, Reminder, ErrorsHandler, $timeout, $uibModal, $DesktopNotification, $AuthUser, ngAudio, $interval) {

    $scope.notifications = 0;
    $scope.reminders = [];

    $scope.$on('popover-shown', function (ev) {
        $scope.notifications = 0;
    });

    $scope.$on('popover-hidden', function () {
        _.each($scope.reminders, function (r) {
            r.highlight = false;
        });
    });

    $scope.load = function (page) {
        if (!page) page = 1;

        Reminder.get({ page: page }, function (response) {
            $scope.reminders = response.data;
            $scope.setAlerts($scope.reminders);
        }, ErrorsHandler);
    };

    $scope.setAlerts = function (reminders) {
        _.each(reminders, function (r) {
            if (r.timeout) $timeout.cancel(r.timeout);

            // Calculate the amount of seconds until it should trigger
            var seconds = moment(r.remind_at).diff(moment(), 'seconds');

            // Postpone function
            var postpone = function (reminder, measurement, value) {

                if (!measurement) measurement = 'minutes';
                if (!value) value = 10;

                return Reminder.update({ id: reminder.id, remind_at: moment(reminder.remind_at).add(measurement, value).format("YYYY-MM-DD HH:mm:ss") }, function (response) {

                    reminder.remind_at = response.remind_at;
                    reminder.notified = false;

                    reminder.alert.update({
                        message: 'Your reminder has been postponed for another ' + value + ' ' + measurement,
                        type: 'success',
                        hideAfter: 3,
                        actions: false
                    });

                    // Cancel the sound
                    if (reminder.sound_loop) {
                        ngAudio.stop('/audio/reminder.mp3');
                        $interval.cancel(reminder.sound_loop);
                    }

                    // Reload all the events
                    $scope.setAlerts($scope.reminders);

                }, ErrorsHandler);
            };

            if (seconds > 0) {
                r.timeout = $timeout(function () {
                    if (r.completed == '1') {
                        r.highlight = true;

                        if (!r.notified) {
                            r.notified = true;
                            $scope.notifications++;
                        }

                        $DesktopNotification.show('Reminder', r.message);

                        // Keep a looping sound going
                        ngAudio.play('/audio/reminder.mp3');
                        if (r.sound_loop) $interval.cancel(r.sound_loop);
                        r.sound_loop = $interval(function () {
                            ngAudio.play('/audio/reminder.mp3');
                        }, 28 * 1000); // 28 seconds long

                        r.alert = Messenger().post({
                            message: moment(r.remind_at).format("HH:mm [- Reminder]") + "<br>" + r.message,
                            type: 'info',
                            hideAfter: 0,
                            actions: {
                                close: {
                                    label: 'Close',
                                    action: function () {
                                        if (r.sound_loop) $interval.cancel(r.sound_loop);

                                        // Hide the alert and stop the sound
                                        r.alert.update({ hideAfter: 1, message: 'Reminder closed.', type: 'success', actions: false });
                                        ngAudio.stop('/audio/reminder.mp3');

                                        // Reload all the events
                                        $timeout(function () {
                                            $scope.setAlerts($scope.reminders);
                                        }, 60 * 1000); // set the reminders timeout again in 60 seconds
                                    }
                                },
                                postponeTenMinutes: {
                                    label: '10m',
                                    action: function () {
                                        postpone(r, 'minutes', 10);
                                    }
                                },
                                postponeOneHour: {
                                    label: '1H',
                                    action: function () {
                                        postpone(r, 'hours', 10);
                                    }
                                },
                                postponeOneDay: {
                                    label: '1D',
                                    action: function () {
                                        postpone(r, 'days', 1);
                                    }
                                }
                            }
                        });
                    }
                }, seconds * 1000);
            }
        });
    };

    $scope.showModal = function (reminder) {
        var modalInstance = $uibModal.open({
            templateUrl: 'reminders/modals/reminder.html',
            controller: 'ReminderModalCtrl'
        });

        modalInstance.result.then(function (response) {
            response.completed = 0;
            $scope.reminders.push(response);
            $scope.setAlerts($scope.reminders);
        });
    };

    $scope.toggleComplete = function (reminder) {
        var status = (reminder.completed == '1') ? 0 : 1;
        Reminder.update({ id: reminder.id, completed: status }, function (response) {
            angular.extend(reminder, response || {});
        }, ErrorsHandler);
    };

    $timeout(function () {
        $scope.load();
    }, 500);

}]);
archDB.directive('reminders', [function () {
    return {
        restrict: 'A',
        controller: 'RemindersCtrl',
        scope: true,
        link: function (scope, iElement, iAttrs) {

        }
    };
}])