"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const electron_1 = require("electron");
const element_ready_1 = require("element-ready");
const selectors_1 = require("./selectors");
const icon = {
    read: 'data-caprine-icon',
    unread: 'data-caprine-icon-unread'
};
const padding = {
    top: 3,
    right: 0,
    bottom: 3,
    left: 0
};
function drawIcon(size, img) {
    const canvas = document.createElement('canvas');
    if (img) {
        canvas.width = size + padding.left + padding.right;
        canvas.height = size + padding.top + padding.bottom;
        const ctx = canvas.getContext('2d');
        ctx.save();
        ctx.beginPath();
        ctx.arc(size / 2 + padding.left, size / 2 + padding.top, size / 2, 0, Math.PI * 2, true);
        ctx.closePath();
        ctx.clip();
        ctx.drawImage(img, padding.left, padding.top, size, size);
        ctx.restore();
    }
    else {
        canvas.width = 0;
        canvas.height = 0;
    }
    return canvas;
}
// Return canvas with rounded image
async function urlToCanvas(url, size) {
    return new Promise(resolve => {
        const img = new Image();
        img.crossOrigin = 'anonymous';
        img.addEventListener('load', () => {
            resolve(drawIcon(size, img));
        });
        img.addEventListener('error', () => {
            console.error('Image not found', url);
            resolve(drawIcon(size));
        });
        img.src = url;
    });
}
async function createIcons(el, url) {
    const canvas = await urlToCanvas(url, 50);
    el.setAttribute(icon.read, canvas.toDataURL());
    const markerSize = 8;
    const ctx = canvas.getContext('2d');
    ctx.fillStyle = '#f42020';
    ctx.beginPath();
    ctx.ellipse(canvas.width - markerSize, markerSize, markerSize, markerSize, 0, 0, 2 * Math.PI);
    ctx.fill();
    el.setAttribute(icon.unread, canvas.toDataURL());
}
async function discoverIcons(el) {
    const profilePicElement = el.querySelector('img:first-of-type');
    if (profilePicElement) {
        return createIcons(el, profilePicElement.src);
    }
    const groupPicElement = el.firstElementChild;
    if (groupPicElement) {
        const groupPicBackground = groupPicElement.style.backgroundImage;
        if (groupPicBackground) {
            return createIcons(el, groupPicBackground.replace(/^url\(["']?(.*?)["']?\)$/, '$1'));
        }
    }
    console.warn('Could not discover profile picture. Falling back to default image.');
    // Fall back to messenger favicon
    const messengerIcon = document.querySelector('link[rel~="icon"]');
    if (messengerIcon) {
        return createIcons(el, messengerIcon.getAttribute('href'));
    }
    // Fall back to facebook favicon
    return createIcons(el, 'https://facebook.com/favicon.ico');
}
async function getIcon(el, unread) {
    if (!el.getAttribute(icon.read)) {
        await discoverIcons(el);
    }
    return el.getAttribute(unread ? icon.unread : icon.read);
}
async function createConversation(el) {
    const conversation = {};
    const muted = el.classList.contains('_569x');
    conversation.selected = el.classList.contains('_1ht2');
    conversation.unread = !muted && el.getAttribute('aria-live') !== null;
    const profileElement = el.querySelector('div[data-tooltip-content]');
    conversation.label = profileElement.getAttribute('data-tooltip-content');
    conversation.icon = await getIcon(profileElement, conversation.unread);
    return conversation;
}
async function createConversationList() {
    const list = await element_ready_1.default(selectors_1.default.conversationList);
    const items = [...list.children];
    const conversations = await Promise.all(items.map(async (element) => createConversation(element)));
    return conversations;
}
async function sendConversationList() {
    electron_1.ipcRenderer.send('conversations', await createConversationList());
}
window.addEventListener('load', async () => {
    const sidebar = document.querySelector('[role=navigation]');
    if (sidebar) {
        await sendConversationList();
        const conversationListObserver = new MutationObserver(sendConversationList);
        conversationListObserver.observe(sidebar, {
            subtree: true,
            childList: true,
            attributes: true,
            attributeFilter: ['class']
        });
    }
});
//# sourceMappingURL=conversation-list.js.map