/*
 * Copyright (c) 2022.
 * Author Peter Placzek (tada5hi)
 * For the full copyright and license information,
 * view the LICENSE file that was distributed with this source code.
 */

import {
    consumeMessageQueue,
    handleMessageQueueChannel,
    QueChannelHandler
} from "../../modules/message-queue";
import {QueueMessage} from "../../modules/message-queue/type";
import {resizeImage} from "./resize-image";
import {writeResizedEvent} from "./write-resized";
import {writeResizeFailedEvent} from "./write-resize-failed";

function createImageComponentHandlers() : Record<string, QueChannelHandler> {
    return {
        resize: async (message: QueueMessage) => {
            return Promise.resolve(message)
                .then(resizeImage)
                .then(writeResizedEvent)
                .catch(err => writeResizeFailedEvent(message, err));
        }
    }
}

export function buildImageComponent() {
    const handlers = createImageComponentHandlers();

    function start() {
        return consumeMessageQueue('image.command', ((async (channel, msg) => {
            try {
                await handleMessageQueueChannel(channel, handlers, msg);
                await channel.ack(msg);
            } catch (e) {
                await channel.reject(msg, false);
            }
        })));
    }

    return {
        start
    }
}
