import { BooleanValue, Schema, StringValue } from "@coveo/bueno";
import { HighlightUtils, ResultTemplatesHelpers } from "@coveo/headless";
import { LitElement, html, nothing } from "lit";
import { customElement, property as decorators_js_property, state } from "lit/decorators.js";
import { when } from "lit/directives/when.js";
import { renderItemTextFallback } from "../../common/item-text/item-text-fallback.js";
import { renderItemTextHighlighted } from "../../common/item-text/item-text-highlighted.js";
import { ValidatePropsController } from "../../common/validate-props-controller/validate-props-controller.js";
import { createResultContextController } from "../result-template-component-utils/context/result-context-controller.js";
import { booleanConverter } from "../../../converters/boolean-converter.js";
import { bindingGuard } from "../../../decorators/binding-guard.js";
import { bindings } from "../../../decorators/bindings.js";
import { errorGuard } from "../../../decorators/error-guard.js";
import { LightDomMixin } from "../../../mixins/light-dom.js";
import { getFieldValueCaption } from "../../../utils/field-utils.js";
import { getStringValueFromResultOrNull } from "../../../utils/result-utils.js";
import "../atomic-text/atomic-text.js";
function _ts_decorate(decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : null === desc ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if ("object" == typeof Reflect && "function" == typeof Reflect.decorate) r = Reflect.decorate(decorators, target, key, desc);
    else for(var i = decorators.length - 1; i >= 0; i--)if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
}
function _ts_metadata(k, v) {
    if ("object" == typeof Reflect && "function" == typeof Reflect.metadata) return Reflect.metadata(k, v);
}
class AtomicResultText extends LightDomMixin(LitElement) {
    initialize() {
        if (!this.result && this.resultController.item) {
            const item = this.resultController.item;
            if ('result' in item) this.result = item.result;
            else this.result = item;
        }
    }
    render() {
        return html`
      ${when(this.result && this.field, ()=>this.renderResultTextValue(), ()=>nothing)}
    `;
    }
    get shouldRenderHighlights() {
        return !this.disableHighlight && this.shouldHighlight && this.isFieldSupportedForHighlighting();
    }
    isFieldSupportedForHighlighting() {
        return [
            'title',
            'excerpt',
            'firstSentences',
            'printableUri',
            'summary'
        ].includes(this.field);
    }
    highlightKeywords() {
        if (!this.shouldRenderHighlights) return null;
        const highlightMap = {
            title: 'titleHighlights',
            excerpt: 'excerptHighlights',
            firstSentences: 'firstSentencesHighlights',
            printableUri: 'printableUriHighlights',
            summary: 'summaryHighlights'
        };
        const highlightPropertyName = highlightMap[this.field];
        if (!highlightPropertyName) return null;
        return ResultTemplatesHelpers.getResultProperty(this.result, highlightPropertyName);
    }
    renderFallback() {
        if (!this.default) return nothing;
        return renderItemTextFallback({
            props: {
                field: this.field,
                host: this,
                logger: this.bindings.engine.logger,
                defaultValue: this.default,
                item: this.result,
                getProperty: (result, property)=>ResultTemplatesHelpers.getResultProperty(result, property)
            }
        })(html`
      <atomic-text
        .value=${getFieldValueCaption(this.field, this.default, this.bindings.i18n)}
      ></atomic-text>
    `);
    }
    renderResultText(textValue) {
        const highlightKeywords = this.highlightKeywords();
        return this.shouldRenderHighlights && highlightKeywords && highlightKeywords.length > 0 ? renderItemTextHighlighted({
            props: {
                textValue,
                highlightKeywords,
                highlightString: HighlightUtils.highlightString,
                onError: (error)=>{
                    this.error = error;
                }
            }
        }) : html`
          <atomic-text
            .value=${getFieldValueCaption(this.field, textValue, this.bindings.i18n)}
          ></atomic-text>
        `;
    }
    renderResultTextValue() {
        const resultValueAsString = getStringValueFromResultOrNull(this.result, this.field);
        if (null === resultValueAsString) return this.renderFallback();
        return this.renderResultText(`${resultValueAsString}`);
    }
    constructor(){
        super(), this.shouldHighlight = true, this.disableHighlight = false, this.resultController = createResultContextController(this);
        new ValidatePropsController(this, ()=>({
                field: this.field,
                shouldHighlight: this.shouldHighlight,
                disableHighlight: this.disableHighlight
            }), AtomicResultText.propsSchema);
    }
}
AtomicResultText.propsSchema = new Schema({
    field: new StringValue({
        required: true,
        emptyAllowed: false
    }),
    shouldHighlight: new BooleanValue(),
    disableHighlight: new BooleanValue()
});
_ts_decorate([
    decorators_js_property({
        type: String,
        reflect: true
    }),
    _ts_metadata("design:type", String)
], AtomicResultText.prototype, "field", void 0);
_ts_decorate([
    decorators_js_property({
        type: Boolean,
        attribute: 'should-highlight',
        reflect: true,
        converter: booleanConverter
    })
], AtomicResultText.prototype, "shouldHighlight", void 0);
_ts_decorate([
    decorators_js_property({
        type: Boolean,
        reflect: true,
        useDefault: true,
        attribute: 'no-highlight'
    }),
    _ts_metadata("design:type", Boolean)
], AtomicResultText.prototype, "disableHighlight", void 0);
_ts_decorate([
    decorators_js_property({
        type: String,
        reflect: true
    }),
    _ts_metadata("design:type", String)
], AtomicResultText.prototype, "default", void 0);
_ts_decorate([
    state(),
    _ts_metadata("design:type", "u" < typeof Result ? Object : Result)
], AtomicResultText.prototype, "result", void 0);
_ts_decorate([
    state(),
    _ts_metadata("design:type", "u" < typeof Bindings ? Object : Bindings)
], AtomicResultText.prototype, "bindings", void 0);
_ts_decorate([
    state(),
    _ts_metadata("design:type", "u" < typeof Error ? Object : Error)
], AtomicResultText.prototype, "error", void 0);
_ts_decorate([
    bindingGuard(),
    errorGuard(),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", []),
    _ts_metadata("design:returntype", void 0)
], AtomicResultText.prototype, "render", null);
AtomicResultText = _ts_decorate([
    customElement('atomic-result-text'),
    bindings(),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", [])
], AtomicResultText);
export { AtomicResultText };
