import { ResultTemplatesHelpers, buildInteractiveResult } from "@coveo/headless";
import { readFromObject } from "./object-utils.js";
function bindLogDocumentOpenOnResult(engine, result, resultElement, selector) {
    const interactiveResult = buildInteractiveResult(engine, {
        options: {
            result
        }
    });
    const eventsMap = {
        contextmenu: ()=>interactiveResult.select(),
        click: ()=>interactiveResult.select(),
        mouseup: ()=>interactiveResult.select(),
        mousedown: ()=>interactiveResult.select(),
        touchstart: ()=>interactiveResult.beginDelayedSelect(),
        touchend: ()=>interactiveResult.cancelPendingSelect()
    };
    const elements = resultElement.querySelectorAll(selector || 'a');
    elements.forEach((element)=>{
        Object.keys(eventsMap).forEach((key)=>element.addEventListener(key, eventsMap[key]));
    });
    return ()=>{
        elements.forEach((element)=>{
            Object.keys(eventsMap).forEach((key)=>element.removeEventListener(key, eventsMap[key]));
        });
    };
}
function buildStringTemplateFromResult(template, result, bindings) {
    return template.replace(/\${(.*?)}/g, (value)=>{
        const key = value.substring(2, value.length - 1);
        let newValue = readFromObject(result, key);
        if (!newValue && "u" > typeof window) newValue = readFromObject(window, key);
        if (!newValue) {
            bindings.engine.logger.warn(`${key} used in the href template is undefined for this result: ${result.uniqueId} and could not be found in the window object.`);
            return '';
        }
        return newValue;
    });
}
function getStringValueFromResultOrNull(result, field) {
    const value = ResultTemplatesHelpers.getResultProperty(result, field);
    if ('string' != typeof value || '' === value.trim()) return null;
    return value;
}
export { bindLogDocumentOpenOnResult, buildStringTemplateFromResult, getStringValueFromResultOrNull };
