import { filter, streamFrom } from "./stream-utils.js";
export function watchIncomingMsgs(msgType) {
    return streamFrom(obs => w3n.mail.inbox.subscribe('message', obs)).pipeThrough(filter(m => (m.msgType === msgType)));
}
export async function sendMsg(msg, progress) {
    if (!msg.recipients || (msg.recipients.length === 0)) {
        throw new Error(`No recicpients given in the message`);
    }
    const recipients = msg.recipients.concat();
    msg.carbonCopy?.forEach(addr => {
        if (!recipients.find(a => areAddressesEqual(a, addr))) {
            recipients.push(addr);
        }
    });
    const deliveryId = `${location.host}${location.pathname}#${Date.now()}-${Math.floor(1000 * Math.random())}`.replaceAll('/', ':');
    await w3n.mail.delivery.addMsg(recipients, msg, deliveryId);
    try {
        await new Promise((resolve, reject) => {
            let isDone = false;
            w3n.mail.delivery.observeDelivery(deliveryId, {
                next: p => {
                    if (isDone) {
                        return;
                    }
                    if (progress) {
                        try {
                            progress(p);
                        }
                        catch (err) {
                            console.error(err);
                        }
                    }
                    if (p.allDone) {
                        isDone = true;
                        if (p.allDone === 'all-ok') {
                            resolve();
                        }
                        else if (p.allDone === 'with-errors') {
                            reject(p);
                        }
                    }
                },
                complete: () => {
                    if (!isDone) {
                        isDone = true;
                        resolve();
                    }
                },
                error: err => {
                    if (!isDone) {
                        isDone = true;
                        reject(err);
                    }
                }
            });
        });
    }
    finally {
        w3n.mail.delivery.rmMsg(deliveryId).catch(err => console.error(err));
    }
}
export function areAddressesEqual(a, b) {
    const canonicalA = toCanonicalAddress(a);
    if (!canonicalA) {
        return false;
    }
    const canonicalB = toCanonicalAddress(b);
    if (!canonicalB) {
        return false;
    }
    return (canonicalA === canonicalB);
}
const whiteSpace = /\s/g;
export function toCanonicalAddress(address) {
    const indOfAt = address.indexOf('@');
    let user;
    let domain;
    if (indOfAt < 0) {
        domain = address;
        user = '';
    }
    else {
        domain = address.substring(indOfAt + 1);
        user = address.substring(0, indOfAt).replace(whiteSpace, '');
    }
    return (user + '@' + domain).toLowerCase();
}
