"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.NotificationApi = exports.deltaVersion = void 0;
const debug_1 = require("../../debug");
const debug = (0, debug_1.createDebug)('signalk-server:api:notification');
const uuid = __importStar(require("uuid"));
const server_api_1 = require("@signalk/server-api");
const __1 = require("..");
const notificationManager_1 = require("./notificationManager");
const SIGNALK_API_PATH = `/signalk/v2/api`;
const NOTI_API_PATH = `${SIGNALK_API_PATH}/notifications`;
exports.deltaVersion = server_api_1.SKVersion.v1;
class NotificationApi {
    server;
    app;
    notiKeys = new Map();
    notificationManager;
    constructor(server) {
        this.server = server;
        this.app = server;
        this.notificationManager = new notificationManager_1.NotificationManager(server);
    }
    async start() {
        return new Promise(async (resolve) => {
            this.initNotificationRoutes();
            this.app.registerDeltaInputHandler((delta, next) => {
                next(this.filterNotifications(delta));
            });
            resolve();
        });
    }
    /** Filter out notifications.* paths and push onto notiUpdate */
    filterNotifications(delta) {
        const notiUpdates = []; // notification updates
        delta.updates =
            delta.updates?.filter((update) => {
                if ((0, server_api_1.hasValues)(update)) {
                    // ignore messages from NotificationManager
                    if ('notificationId' in update) {
                        return true;
                    }
                    // filter out values containing notification paths
                    const filteredValues = update.values.filter((u) => {
                        if (u.path.startsWith('notifications')) {
                            const nu = Object.assign({}, update, { values: [u] });
                            notiUpdates.push(nu);
                            return false;
                        }
                        else {
                            return true;
                        }
                    });
                    if (filteredValues.length) {
                        update.values = filteredValues;
                        return true;
                    }
                    else {
                        return false;
                    }
                }
                return true;
            }) ?? [];
        notiUpdates.forEach((update) => {
            this.handleNotificationUpdate(update, delta.context);
        });
        return delta;
    }
    /**
     * Handle incoming notification update and assign a notification identifier
     * @param update Update object
     * @param context Context value
     */
    handleNotificationUpdate(update, context) {
        if ((0, server_api_1.hasValues)(update) && update.values.length) {
            const path = update.values[0].path;
            const src = update['$source'];
            const key = (0, notificationManager_1.buildKey)(context, path, src);
            if (this.notiKeys.has(key)) {
                update.notificationId = this.notiKeys.get(key);
            }
            else {
                update.notificationId = uuid.v4();
                this.notiKeys.set(key, update.notificationId);
            }
            // register with manager
            this.notificationManager.processNotificationUpdate(update, context);
        }
    }
    /** Initialise API endpoints */
    initNotificationRoutes() {
        // Return list of notifications
        this.app.get(`${NOTI_API_PATH}`, async (req, res) => {
            debug(`** ${req.method} ${req.path}`);
            res.status(200).json(this.listNotifications());
        });
        // fetch
        this.app.get(`${NOTI_API_PATH}/:id`, async (req, res) => {
            debug(`** ${req.method} ${req.path}`);
            const n = this.getNotification(req.params.id);
            if (n) {
                res.status(200).json(n);
            }
            else {
                res.status(200).json(__1.Responses.notFound);
            }
        });
        // Silence All
        this.app.post(`${NOTI_API_PATH}/silenceAll`, async (req, res) => {
            debug(`** ${req.method} ${req.path}`);
            try {
                this.silenceAll();
                res.status(200).json(__1.Responses.ok);
            }
            catch (err) {
                res.status(400).json({
                    state: 'FAILED',
                    statusCode: 400,
                    message: err.message
                });
            }
        });
        // Silence
        this.app.post(`${NOTI_API_PATH}/:id/silence`, async (req, res) => {
            debug(`** ${req.method} ${req.path}`);
            try {
                this.silenceNotification(req.params.id);
                res.status(200).json(__1.Responses.ok);
            }
            catch (err) {
                res.status(400).json({
                    state: 'FAILED',
                    statusCode: 400,
                    message: err.message
                });
            }
        });
        // Acknowledge All
        this.app.post(`${NOTI_API_PATH}/acknowledgeAll`, async (req, res) => {
            debug(`** ${req.method} ${req.path}`);
            try {
                this.acknowledgeAll();
                res.status(200).json(__1.Responses.ok);
            }
            catch (err) {
                res.status(400).json({
                    state: 'FAILED',
                    statusCode: 400,
                    message: err.message
                });
            }
        });
        // Acknowledge
        this.app.post(`${NOTI_API_PATH}/:id/acknowledge`, async (req, res) => {
            debug(`** ${req.method} ${req.path}`);
            try {
                this.acknowledgeNotification(req.params.id);
                res.status(200).json(__1.Responses.ok);
            }
            catch (err) {
                res.status(400).json({
                    state: 'FAILED',
                    statusCode: 400,
                    message: err.message
                });
            }
        });
        // Clear
        this.app.delete(`${NOTI_API_PATH}/:id`, async (req, res) => {
            debug(`** ${req.method} ${req.path}`);
            try {
                this.clearNotification(req.params.id);
                res.status(200).json(__1.Responses.ok);
            }
            catch (err) {
                res.status(400).json({
                    state: 'FAILED',
                    statusCode: 400,
                    message: err.message
                });
            }
        });
        // raise
        this.app.post(`${NOTI_API_PATH}`, async (req, res) => {
            debug(`** ${req.method} ${req.path} ${req.body}`);
            try {
                const id = this.notificationManager.raise(req.body);
                res.status(200).json(Object.assign({}, __1.Responses.ok, { id: id }));
            }
            catch (err) {
                res.status(400).json({
                    state: 'FAILED',
                    statusCode: 400,
                    message: err.message
                });
            }
        });
        // update
        this.app.put(`${NOTI_API_PATH}/:id`, async (req, res) => {
            debug(`** ${req.method} ${req.path} ${req.body}`);
            try {
                this.updateNotification(req.params.id, req.body);
                res.status(200).json(__1.Responses.ok);
            }
            catch (err) {
                res.status(400).json({
                    state: 'FAILED',
                    statusCode: 400,
                    message: err.message
                });
            }
        });
        // MOB notification
        this.app.post(`${NOTI_API_PATH}/mob`, async (req, res) => {
            debug(`** ${req.method} ${req.path} ${req.body}`);
            try {
                const id = this.notificationManager.mob(req.body);
                res.status(200).json(Object.assign({}, __1.Responses.ok, { id: id }));
            }
            catch (err) {
                res.status(400).json({
                    state: 'FAILED',
                    statusCode: 400,
                    message: err.message
                });
            }
        });
    }
    //** Plugin Interface Methods */
    listNotifications() {
        return this.notificationManager.list;
    }
    getNotification(id) {
        return this.notificationManager.get(id);
    }
    silenceNotification(id) {
        this.notificationManager.silence(id);
    }
    silenceAll() {
        this.notificationManager.silenceAll();
    }
    acknowledgeNotification(id) {
        this.notificationManager.acknowledge(id);
    }
    acknowledgeAll() {
        this.notificationManager.acknowledgeAll();
    }
    clearNotification(id) {
        this.notificationManager.clear(id);
    }
    raiseNotification(options) {
        return this.notificationManager.raise(options);
    }
    updateNotification(id, options) {
        this.notificationManager.update(id, options);
    }
    mob(message) {
        return this.notificationManager.mob({ message: message });
    }
}
exports.NotificationApi = NotificationApi;
//# sourceMappingURL=index.js.map