import { SendableMessageInfo } from "@azure/service-bus";
import { AzureServiceBusSenderInt } from "./index";

export class ASBInMemory implements AzureServiceBusSenderInt {
    public messages: any[];

    constructor() {
        this.messages = [];
    }

    maxBatch(): number {
        return 5;
    }

    last() {
        return this.messages.slice(-1)[0];
    }

    clear() {
        this.messages = [];
    }

    async sendToTopic(topicName: string, message: SendableMessageInfo): Promise<void> {
        // insert the topic in the message to leave trace about it
        // this is only for this in-memory object
        (<any>message)._topicName = topicName;
        this.messages.push(message);
    }

    async sendToQueue(queueName: string, message: SendableMessageInfo): Promise<void> {
        // insert the queue in the message to leave trace about it
        // this is only for this in-memory object
        (<any>message)._queueName = queueName;
        this.messages.push(message);
    }

    private injectMessage(msg: SendableMessageInfo, moreProperties?: any): SendableMessageInfo {
        msg.contentType = 'application/json';
        msg.userProperties = msg.userProperties || {};
        msg.userProperties.senderName = 'asb-inmemory';

        if (moreProperties) {
            Object.assign(msg.userProperties, moreProperties);
        }

        return msg;
    }

    async sendBatchToTopic(topicName: string, messages: SendableMessageInfo[], moreProperties?: any): Promise<void> {
        if (messages.length > this.maxBatch()) {
            throw new Error(`batch can only be up to ${this.maxBatch} messages`);
        }

        messages.forEach(m => {
            (<any>m)._topicName = topicName;
            this.injectMessage(m, moreProperties)
        });
        this.messages.push(...messages);
    }

    async sendBatchToQueue(queueName: string, messages: SendableMessageInfo[], moreProperties?: any): Promise<void> {
        if (messages.length > this.maxBatch()) {
            throw new Error(`batch can only be up to ${this.maxBatch} messages`);
        }

        messages.forEach(m => {
            (<any>m)._queueName = queueName;
            this.injectMessage(m, moreProperties)
        });
        this.messages.push(...messages);
    }
}
