import { Schema, StringValue } from "@coveo/bueno";
import { ResultTemplatesHelpers } from "@coveo/headless";
import { LitElement, html } from "lit";
import { customElement, property, state } from "lit/decorators.js";
import { defaultNumberFormatter } from "../../common/formats/format-common.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 { bindingGuard } from "../../../decorators/binding-guard.js";
import { bindings } from "../../../decorators/bindings.js";
import { errorGuard } from "../../../decorators/error-guard.js";
import { InitializeBindingsMixin } from "../../../mixins/bindings-mixin.js";
import { LightDomMixin } from "../../../mixins/light-dom.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 AtomicResultNumber extends LightDomMixin(InitializeBindingsMixin(LitElement)) {
    connectedCallback() {
        super.connectedCallback();
        this.addEventListener('atomic/numberFormat', this.handleNumberFormat);
    }
    disconnectedCallback() {
        super.disconnectedCallback();
        this.removeEventListener('atomic/numberFormat', this.handleNumberFormat);
    }
    initialize() {}
    render() {
        const valueToDisplay = this.getValueToDisplay();
        if (null === valueToDisplay) {
            this.remove();
            return html``;
        }
        return html`${valueToDisplay}`;
    }
    parseValue() {
        const value = ResultTemplatesHelpers.getResultProperty(this.result, this.field);
        if (null === value) return null;
        const valueAsNumber = parseFloat(`${value}`);
        if (Number.isNaN(valueAsNumber)) throw new Error(`Could not parse "${value}" from field "${this.field}" as a number.`);
        return valueAsNumber;
    }
    formatValue(value) {
        try {
            return this.formatter(value, this.bindings.i18n.languages);
        } catch (error) {
            this.error = error;
            return value.toString();
        }
    }
    getValueToDisplay() {
        try {
            const value = this.parseValue();
            if (null === value) return null;
            return this.formatValue(value);
        } catch (error) {
            this.error = error;
        }
    }
    get result() {
        return this.resultContext.item;
    }
    constructor(){
        super(), this.formatter = defaultNumberFormatter, this.resultContext = createResultContextController(this), this.handleNumberFormat = (event)=>{
            const customEvent = event;
            customEvent.preventDefault();
            customEvent.stopPropagation();
            this.formatter = customEvent.detail;
        };
        new ValidatePropsController(this, ()=>({
                field: this.field
            }), AtomicResultNumber.propsSchema);
    }
}
AtomicResultNumber.propsSchema = new Schema({
    field: new StringValue({
        emptyAllowed: false,
        required: true
    })
});
_ts_decorate([
    property({
        reflect: true
    }),
    _ts_metadata("design:type", String)
], AtomicResultNumber.prototype, "field", void 0);
_ts_decorate([
    state(),
    _ts_metadata("design:type", "u" < typeof Bindings ? Object : Bindings)
], AtomicResultNumber.prototype, "bindings", void 0);
_ts_decorate([
    state(),
    _ts_metadata("design:type", "u" < typeof Error ? Object : Error)
], AtomicResultNumber.prototype, "error", void 0);
_ts_decorate([
    state(),
    _ts_metadata("design:type", "u" < typeof NumberFormatter ? Object : NumberFormatter)
], AtomicResultNumber.prototype, "formatter", void 0);
_ts_decorate([
    bindingGuard(),
    errorGuard(),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", []),
    _ts_metadata("design:returntype", void 0)
], AtomicResultNumber.prototype, "render", null);
AtomicResultNumber = _ts_decorate([
    customElement('atomic-result-number'),
    bindings(),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", [])
], AtomicResultNumber);
export { AtomicResultNumber };
