/*
 * Copyright (C) 2024 Tildeslash Ltd. All rights reserved.
 */


(function ($) {
    // See also apperance.js
    const changeAppearance = (newAppearance) => {
        const htmlElement = document.documentElement;
        const change = (appearance) => {
            htmlElement.classList.remove('dark', 'light');
            if (appearance === 2) {
                htmlElement.classList.add('dark');
            } else if (appearance === 1) {
                htmlElement.classList.add('light');
            } else {
                htmlElement.classList.add(
                    window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'
                );
            }
            localStorage.setItem('appearance', appearance);
        };

        if (document.startViewTransition) {
            document.startViewTransition(() => change(newAppearance));
        } else {
            change(newAppearance);
        }
    };
    
    var ViewModel = new function () {
        var self = this;

        self.width = ko.observable($('#main').outerWidth());
        self.showCheckUpdatesWarning = ko.observable(false);
        self.checkUpdatesStatus = ko.observable();
        self.defaultSkew = ko.observable().extend({number:true, min:1});

        self.loading = ko.observable(true);

        self.deleteEventsMenu = ko.observableArray(Menu.JSONToMenu([
            {id: '5',  name: "After 1 month",  description: "1 month"},
            {id: '6',  name: "After 3 months", description: "3 months"},
            {id: '7',  name: "After 6 months", description: "6 months"},
            {id: '8',  name: "After 1 year",   description: "1 year"},
            {id: '9',  name: "After 3 years",  description: "3 years"},
            {id: '10', name: "Never",          description: "never"}
        ]));
        self.deleteEventsLabel = ko.computed(function () {
            return Menu.getSelectedNames(self.deleteEventsMenu(), null);
        });

        self.deleteAnalyticsMenu = ko.observableArray(Menu.JSONToMenu([
            {id: '5',  name: "After 1 month",  description: "1 month"},
            {id: '6',  name: "After 3 months", description: "3 months"},
            {id: '7',  name: "After 6 months", description: "6 months"},
            {id: '8',  name: "After 1 year",   description: "1 year"},
            {id: '9',  name: "After 3 years",  description: "3 years"}
        ]));
        self.deleteAnalyticsLabel = ko.computed(function () {
            return Menu.getSelectedNames(self.deleteAnalyticsMenu(), null);
        });

        self.appearanceMenu = ko.observableArray(Menu.JSONToMenu([
            {id: '0',  name: "Auto"},
            {id: '1',  name: "Light"},
            {id: '2',  name: "Dark"},
        ]));
        self.appearanceLabel = ko.computed(function () {
            return Menu.getSelectedNames(self.appearanceMenu(), null);
        });

        // Methods
        self.serialize = function () {
            return {
                "auditdefaultpassword": self.systemmessages.auditDefaultPassword(),
                "auditmd5password":     self.systemmessages.auditMD5Password(),
                "versioncheckmonit":    self.systemmessages.newMonitNotification(),
                "versioncheckmmonit":   self.systemmessages.newMMonitNotification(),
                "purgeevents":          Menu.getSelectedValues(self.deleteEventsMenu(), 'id')[0],
                "purgeanalytics":       Menu.getSelectedValues(self.deleteAnalyticsMenu(), 'id')[0],
                "defaultskew":          self.defaultSkew()
            }
        };

        self.setVersionCheckStatus = function (message) {
            self.checkUpdatesStatus(message);
            if (self.systemmessages.newMonitNotification() || self.systemmessages.newMMonitNotification()) {
                if (message == "") {
                    self.checkUpdatesStatus("Initializing");
                    self.showCheckUpdatesWarning(false);
                } else if (message != "Success") {
                    self.showCheckUpdatesWarning(true);
                } else {
                    self.showCheckUpdatesWarning(false);
                }
            } else {
                self.showCheckUpdatesWarning(false);
            }
        };

        self.update = function () {
            if (! self.loading()) {
                $.ajax({
                    url:  "../../admin/settings/update",
                    data: self.serialize(),
                    type: 'POST',
                    timeout: 30000,
                    error: MMONIT.error.json,
                    success: function (data, textStatus, jqXHR) {
                        var response = $.parseJSON(data);
                        self.setVersionCheckStatus(response.description);
                    }
                });
            }
        };

        self.systemmessages = {
            // Properties
            auditDefaultPassword:  ko.observable(false),
            auditMD5Password:      ko.observable(false),
            newMMonitNotification: ko.observable(false),
            newMonitNotification:  ko.observable(false),

            // Password audit
            toggleAuditDefaultPassword: function (data, e) {
                e.stopPropagation();
                self.systemmessages.auditDefaultPassword(! self.systemmessages.auditDefaultPassword());
                self.update();
            },
            toggleAuditMD5Password: function (data, e) {
                e.stopPropagation();
                self.systemmessages.auditMD5Password(! self.systemmessages.auditMD5Password());
                self.update();
            },

            // New release notification
            toggleNewMMonitNotification: function (data, e) {
                e.stopPropagation();
                self.systemmessages.newMMonitNotification(! self.systemmessages.newMMonitNotification());
                self.update();
            },
            toggleNewMonitNotification: function (data, e) {
                e.stopPropagation();
                self.systemmessages.newMonitNotification(! self.systemmessages.newMonitNotification());
                self.update();
            }
        };

        // Warning methods
        self.displayCheckUpdatesWarning = function (data, e) {
            e.stopPropagation();
            $(e.currentTarget).tooltip('show');
        };
        self.hideCheckUpdatesWarning = function (data, e) {
            e.stopPropagation();
            $(e.currentTarget).tooltip('hide');
        };

        // Data retention
        self.purgeEventsSelection = ko.observable(self.deleteEventsMenu().length - 1);
        self.selectPurgeEvents = function (row) {
            if (row.id === Menu.getSelectedValues(self.deleteEventsMenu(), 'id')[0])
                return
            self.purgeEventsSelection(row);
            // If the selection is 'Never', do not display the delete confirmation dialog
            if (row.id == '10')
                self.selectPurgeEventsConfirm();
            else
                $('#confirmDeleteEvents').modal('show');
        };
        self.selectPurgeEventsConfirm = function () {
            Menu.select(self.deleteEventsMenu(), self.purgeEventsSelection().id);
            self.update();
        };
        self.purgeAnalyticsSelection = ko.observable(self.deleteAnalyticsMenu.length - 1);
        self.selectPurgeAnalytics = function (row) {
            if (row.id === Menu.getSelectedValues(self.deleteAnalyticsMenu(), 'id')[0])
                return
            self.purgeAnalyticsSelection(row);
            $('#confirmDeleteAnalytics').modal('show');
        };
        self.selectPurgeAnalyticsConfirm = function (row) {
            Menu.select(self.deleteAnalyticsMenu(), self.purgeAnalyticsSelection().id);
            self.update();
        };
        self.setDefaultSkew = function (data, e) {
            e.stopPropagation();
            self.update();
        };
        // User select appearance (dark/light mode). We don't use 
        // The HTTP API but javascript localStorage to store the value
        const appearance = localStorage.getItem("appearance") || 0;
        self.selectAppearance = function (row) {
            const newAppearance = Number(row.id);
            if (newAppearance !== appearance) {
                changeAppearance(newAppearance);
                Menu.select(self.appearanceMenu(), newAppearance);
            }
        };
        Menu.select(self.appearanceMenu(), appearance);
        
        $.ajax({
            url: "../../admin/settings/get",
            type: 'GET',
            dataType: 'json',
            timeout: 30000,
            error: MMONIT.error.json,
            success: function (data) {
                self.systemmessages.auditDefaultPassword(data.audit.defaultpassword);
                self.systemmessages.auditMD5Password(data.audit.md5password);
                self.systemmessages.newMonitNotification(data.versioncheck.monit);
                self.systemmessages.newMMonitNotification(data.versioncheck.mmonit);
                self.setVersionCheckStatus(data.versioncheck.status);
                Menu.select(self.deleteEventsMenu(), data.dataretention.purgeevents);
                Menu.select(self.deleteAnalyticsMenu(), data.dataretention.purgeanalytics);
                self.defaultSkew(data.hosts.defaultskew);
                self.loading(false);
            }
        });

    } // ViewModel

    // Activate knockout.js
    ko.applyBindings(ViewModel);

    // RESPONSIVE settings
    $(window).on('resize orientationchange', function (e) {
        ViewModel.width($('#main').outerWidth());
    });
})(jQuery);
