"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 (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
const electron_1 = require("electron");
const eventType_1 = require("../../lib/eventType");
const locale = __importStar(require("../../locale"));
const config_1 = require("../../settings/config");
const remote = require('@electron/remote');
const savePicture = (url, timestamp) => __awaiter(void 0, void 0, void 0, function* () {
    const response = yield fetch(url, {
        headers: {
            'User-Agent': config_1.config.userAgent,
        },
    });
    const bytes = yield response.arrayBuffer();
    electron_1.ipcRenderer.send(eventType_1.EVENT_TYPE.ACTION.SAVE_PICTURE, new Uint8Array(bytes), timestamp);
});
const copyPicture = (url) => __awaiter(void 0, void 0, void 0, function* () {
    const response = yield fetch(url, {
        headers: {
            'User-Agent': config_1.config.userAgent,
        },
    });
    const bytes = yield response.arrayBuffer();
    const image = electron_1.nativeImage.createFromBuffer(Buffer.from(bytes));
    electron_1.clipboard.writeImage(image);
});
const createDefaultMenu = (copyContext) => remote.Menu.buildFromTemplate([
    {
        click: () => electron_1.clipboard.writeText(copyContext),
        label: locale.getText('menuCopy'),
    },
]);
const createTextMenu = (params, webContents) => {
    const { editFlags, dictionarySuggestions } = params;
    const template = [
        {
            click: (_menuItem, browserWindow) => browserWindow === null || browserWindow === void 0 ? void 0 : browserWindow.webContents.send(eventType_1.EVENT_TYPE.EDIT.CUT),
            enabled: editFlags.canCut,
            label: locale.getText('menuCut'),
        },
        {
            click: (_menuItem, browserWindow) => browserWindow === null || browserWindow === void 0 ? void 0 : browserWindow.webContents.send(eventType_1.EVENT_TYPE.EDIT.COPY),
            enabled: editFlags.canCopy,
            label: locale.getText('menuCopy'),
        },
        {
            click: (_menuItem, browserWindow) => browserWindow === null || browserWindow === void 0 ? void 0 : browserWindow.webContents.send(eventType_1.EVENT_TYPE.EDIT.PASTE),
            enabled: editFlags.canPaste,
            label: locale.getText('menuPaste'),
        },
        {
            type: 'separator',
        },
        {
            click: (_menuItem, browserWindow) => browserWindow === null || browserWindow === void 0 ? void 0 : browserWindow.webContents.send(eventType_1.EVENT_TYPE.EDIT.SELECT_ALL),
            enabled: editFlags.canSelectAll,
            label: locale.getText('menuSelectAll'),
        },
    ];
    if (dictionarySuggestions.length > 0) {
        template.push({
            type: 'separator',
        });
        for (const suggestion of dictionarySuggestions) {
            template.push({
                click: () => webContents.replaceMisspelling(suggestion),
                label: suggestion,
            });
        }
    }
    return remote.Menu.buildFromTemplate(template);
};
const imageMenu = remote.Menu.buildFromTemplate([
    {
        click: () => savePicture(imageMenu.image || ''),
        label: locale.getText('menuSavePictureAs'),
    },
    {
        click: () => copyPicture(imageMenu.image || ''),
        label: locale.getText('menuCopyPicture'),
    },
]);
const webContents = remote.getCurrentWebContents();
webContents.on('context-menu', (_event, params) => {
    const window = remote.getCurrentWindow();
    if (params.isEditable) {
        const textMenu = createTextMenu(params, webContents);
        textMenu.popup({ window });
    }
    else if (params.mediaType === 'image') {
        imageMenu.image = params.srcURL;
        imageMenu.popup({ window });
    }
    else if (!!params.linkURL) {
        const copyContext = params.linkURL.replace(/^mailto:/, '');
        createDefaultMenu(copyContext).popup({ window });
    }
    else if (!!params.selectionText || params.editFlags.canCopy) {
        const copyContext = params.selectionText;
        createDefaultMenu(copyContext).popup({ window });
    }
    else if (params.editFlags.canSelectAll) {
        let element = document.elementFromPoint(params.x, params.y);
        while (element && element !== document && !element.classList.contains('text')) {
            element = element.parentNode;
        }
        if (element) {
            const copyContext = (params.selectionText || '').toString() || (element.innerText || '').trim();
            if (copyContext) {
                createDefaultMenu(copyContext).popup({ window });
            }
        }
    }
});
//# sourceMappingURL=preload-context.js.map