import {
    equalActionPresetValues,
    equalTimePresetValues
} from './core-utils.mjs.js';
import { createLogger } from './logger.mjs.js';
import { pluralize } from './string-utils.mjs.js';

const logger = createLogger('modules/ui-utils');

export const appendI18n = element => {
    if (!element) {
        return;
    }

    if (element.hasAttribute('data-i18n')) {
        const _i18n = element.getAttribute('data-i18n');
        const text = browser.i18n.getMessage(_i18n);

        const node = document.createTextNode(text);
        element.insertBefore(node, element.firstChild);
    }
};

export const translateDocument = doc => {
    const nodes = (doc || document).querySelectorAll('[data-i18n]');
    const translateableNodes = Array.from(nodes);

    translateableNodes.forEach(appendI18n);
};

export const createTimePresetPicker = (element, timePresets) => {
    Array.from(element.children).forEach(item => item.remove());
    timePresets.map(timePreset => {
        const timeOption = document.createElement('option');
        if (!timePreset.isSelectable) {
            timeOption.disabled = true;
        }

        timeOption.innerText = timePreset.text;
        timeOption.value = JSON.stringify(timePreset);

        element.appendChild(timeOption);
    });

    return element;
};

export const selectDefaultTimePreset = (timePresets, defaultTimePreset) => {
    const availablePresets = Array.from(timePresets.options)
        .map(item => ({
            index: item.index,
            timePreset: JSON.parse(item.value)
        }))
        .filter(
            ({ timePreset }) =>
                timePreset.isSelectable &&
                equalTimePresetValues(timePreset, defaultTimePreset)
        )
        .map(({ index }) => index);
    const selectedIndex = availablePresets.shift() || 1;
    timePresets.selectedIndex = selectedIndex;
};

export const selectDefaultActionPreset = (element, defaultActionPreset) => {
    const presetsFromOptions = Array.from(element.options).map(item => ({
        index: item.index,
        actionPreset: JSON.parse(item.value)
    }));
    const availablePresets = presetsFromOptions
        .filter(({ actionPreset }) =>
            // 
            areActionsEqual(actionPreset, defaultActionPreset, true)
        )
        .map(({ index }) => index);
    const selectedIndex = availablePresets.shift() || 0;

    element.selectedIndex = selectedIndex;
};

export const areActionsEqual = (
    someAction,
    someOtherAction,
    ignoreShowReminder = false
) => {
    if (!someAction || !someOtherAction) {
        return false;
    }

    const props = [
        'flag',
        'markUnread',
        'tagWithLabel',
        'copyMessageTo',
        'moveMessageTo',
        ignoreShowReminder ? void 0 : 'showReminder'
    ];

    let result = true;
    props.forEach(prop => {
        let equal = someAction[prop] === someOtherAction[prop];
        if (!equal) {
            logger.info(
                `prop '${prop}' failed: '${someAction[prop]}' !== '${someOtherAction[prop]}'`
            );
            result = result && false;
        }
    });

    logger.info(`--- checks: ${result}`);
    return result;
};

/**
 * Selects the index of an action preset from a list of action presets
 * @param {Array<{ readonly index: number; readonly actionPreset: MailmindrAction }>} list
 * @param {MailmindrAction} defaultActionPreset
 */
export const selectDefaultActionPresetIndexFromList = (
    list,
    defaultActionPreset
) => {
    const availablePresets = list
        .filter(({ actionPreset }) =>
            equalActionPresetValues(actionPreset, defaultActionPreset)
        )
        .map(({ index }) => index);
    const selectedIndex = availablePresets.shift() || 0;

    return selectedIndex;
};

export const selectDefaultRemindeMeMinutesBeforePreset = (
    element,
    presets,
    selectedRemindMeBeforeValue
) => {
    const remindMeMinutesBefore = presets;
    if (selectedRemindMeBeforeValue !== null) {
        const selectedIndex = remindMeMinutesBefore.findIndex(
            item =>
                parseInt(item.minutes, 10) ===
                parseInt(selectedRemindMeBeforeValue, 10)
        );
        if (selectedIndex >= 0) {
            element.selectedIndex = selectedIndex;
        }
    }
};

export const createRemindMeBeforePicker = (
    document,
    element,
    presets,
    selectedRemindMeBeforeValue = null
) => {
    const remindMeMinutesBefore = presets;
    remindMeMinutesBefore.forEach(item => {
        const option = document.createElement('option');
        const { minutes, unit, display: displayedValue } = item;

        option.value = String(minutes);

        if (unit === 'on-time') {
            option.innerText = pluralize(
                displayedValue,
                'mailmindr.utils.core.remindme.before.on-time'
            );
        } else if (unit === 'minutes') {
            option.innerText = pluralize(
                displayedValue,
                'mailmindr.utils.core.remindme.before.minutes'
            );
        } else if (unit === 'hours') {
            option.innerText = pluralize(
                displayedValue,
                'mailmindr.utils.core.remindme.before.hours'
            );
        } else if (unit === 'no-reminder') {
            option.innerText = pluralize(
                displayedValue,
                'mailmindr.utils.core.remindme.before.no-reminder'
            );
        }
        element.appendChild(option);
    });

    selectDefaultRemindeMeMinutesBeforePreset(
        element,
        presets,
        selectedRemindMeBeforeValue
    );
};

// 
// 
// 
// 
// 
// 
// 
// 
// 

// 
// 
// 

// 
// 
// 
// 
// 
// 

// 
// 
// 
// 

export const webHandler = sender => {
    const { target } = sender;
    if (target) {
        const { web } = target.dataset;

        if (web && web.startsWith('https://')) {
            browser.windows.openDefaultBrowser(web);
        }
    }
};

export const clearContents = parentElement => {
    Array.from(parentElement.children).forEach(child => child.remove());
};

export const isDarkMode = () => {
    const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
    return mediaQuery.matches;
};
