import * as i0 from '@angular/core';
import { inject, Input, Component } from '@angular/core';
import * as i2 from '@angular/forms';
import { FormBuilder, NgForm, Validators, ControlContainer, ReactiveFormsModule } from '@angular/forms';
import * as i1 from '@c8y/ngx-components';
import { CoreModule, CommonModule, C8yTranslatePipe } from '@c8y/ngx-components';
import { gettext } from '@c8y/ngx-components/gettext';
import { a as RESULT_TYPES, F as FieldbusService } from './c8y-ngx-components-computed-asset-properties-c8y-ngx-components-computed-asset-properties-wNQ45CJ1.mjs';
import * as i2$1 from '@angular/common';

class FieldbusItemStatusConfigComponent {
    constructor() {
        this.resultTypes = RESULT_TYPES;
        this.groupedItems = [];
        this.fieldbusService = inject(FieldbusService);
        this.formBuilder = inject(FormBuilder);
        this.form = inject(NgForm);
    }
    ngOnInit() {
        this.initForm();
    }
    async ngOnChanges(changes) {
        if (changes['asset'] && this.asset) {
            try {
                this.deviceType = await this.fieldbusService.getDeviceTypeOf(this.asset);
                this.buildGroupedItemsFromDeviceType();
                this.patchFormFromConfig();
            }
            catch (err) {
                this.deviceType = null;
                this.groupedItems = [];
                this.formGroup.reset();
            }
        }
        if (changes['config'] && this.config) {
            this.patchFormFromConfig();
        }
    }
    ngOnDestroy() {
        this.form.form.removeControl('config');
    }
    onBeforeSave(config) {
        if (this.formGroup.valid) {
            Object.assign(config, this.formToConfig());
            return true;
        }
        return false;
    }
    initForm() {
        this.formGroup = this.createForm();
        this.form.form.addControl('config', this.formGroup);
        this.formGroup.patchValue({ item: null, resultType: RESULT_TYPES.RAW_VALUE.value });
        this.patchFormFromConfig();
    }
    createForm() {
        return this.formBuilder.group({
            item: [null, [Validators.required]],
            resultType: ['', [Validators.required]]
        });
    }
    formToConfig() {
        const formValue = this.formGroup.value;
        if (!formValue.item)
            return null;
        const item = formValue.item;
        const itemName = item.name;
        const itemType = this.groupedItems.find(g => g.items.includes(item))?.type;
        const resultType = formValue.resultType;
        return { itemName, itemType, resultType };
    }
    patchFormFromConfig() {
        if (!this.config || !this.groupedItems.length || !this.formGroup)
            return;
        const { itemType, itemName, resultType } = this.config;
        let foundItem = null;
        for (const group of this.groupedItems) {
            foundItem = group.items.find(item => group.type === itemType && item.name === itemName);
            if (foundItem)
                break;
        }
        if (foundItem) {
            this.formGroup.patchValue({ item: foundItem, resultType });
        }
        else {
            this.formGroup.patchValue({ item: null, resultType: RESULT_TYPES.RAW_VALUE.value });
        }
    }
    buildGroupedItemsFromDeviceType() {
        this.groupedItems = [];
        if (!this.deviceType)
            return;
        if (this.deviceType.c8y_Coils?.length) {
            this.groupedItems.push({
                type: 'c8y_Coil',
                label: gettext('Coils'),
                items: this.deviceType.c8y_Coils
            });
        }
        if (this.deviceType.c8y_Registers?.length) {
            this.groupedItems.push({
                type: 'c8y_Register',
                label: gettext('Registers'),
                items: this.deviceType.c8y_Registers
            });
        }
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: FieldbusItemStatusConfigComponent, deps: [], target: i0.ɵɵFactoryTarget.Component }); }
    static { this.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "20.3.19", type: FieldbusItemStatusConfigComponent, isStandalone: true, selector: "c8y-fieldbus-item-status-config", inputs: { config: "config", asset: "asset" }, usesOnChanges: true, ngImport: i0, template: "<form [formGroup]=\"formGroup\">\n  <div class=\"d-flex-md row\">\n    <div class=\"col-md-6\">\n      <c8y-form-group style=\"padding-top: var(--c8y-font-size-base)\">\n        <label for=\"fieldbusItem\">{{ 'Fieldbus item' | translate }}</label>\n        <div class=\"c8y-select-wrapper\">\n          <select\n            class=\"form-control\"\n            id=\"fieldbusItem\"\n            formControlName=\"item\"\n          >\n            @for (group of groupedItems; track group.label) {\n              <optgroup [label]=\"group.label | translate\">\n                @for (item of group.items; track item.name) {\n                  <option [ngValue]=\"item\">\n                    {{ item.name }}\n                  </option>\n                }\n              </optgroup>\n            }\n          </select>\n        </div>\n        <c8y-messages\n          [show]=\"formGroup.controls?.item?.touched ? formGroup?.controls?.item?.errors : {}\"\n        ></c8y-messages>\n      </c8y-form-group>\n    </div>\n    <div class=\"col-md-6\">\n      <c8y-form-group style=\"padding-top: var(--c8y-font-size-base)\">\n        <label for=\"resultType\">{{ 'Result type' | translate }}</label>\n        <div class=\"c8y-select-wrapper\">\n          <select\n            class=\"form-control\"\n            id=\"resultType\"\n            formControlName=\"resultType\"\n          >\n            @for (resultType of resultTypes | keyvalue; track resultType.key) {\n              <option [ngValue]=\"resultType.value.value\">\n                {{ resultType.value.label | translate }}\n              </option>\n            }\n          </select>\n        </div>\n      </c8y-form-group>\n    </div>\n  </div>\n</form>\n", dependencies: [{ kind: "ngmodule", type: CoreModule }, { kind: "directive", type: i2.ɵNgNoValidate, selector: "form:not([ngNoForm]):not([ngNativeValidate])" }, { kind: "directive", type: i2.NgSelectOption, selector: "option", inputs: ["ngValue", "value"] }, { kind: "directive", type: i2.ɵNgSelectMultipleOption, selector: "option", inputs: ["ngValue", "value"] }, { kind: "directive", type: i2.SelectControlValueAccessor, selector: "select:not([multiple])[formControlName],select:not([multiple])[formControl],select:not([multiple])[ngModel]", inputs: ["compareWith"] }, { kind: "directive", type: i2.NgControlStatus, selector: "[formControlName],[ngModel],[formControl]" }, { kind: "directive", type: i2.NgControlStatusGroup, selector: "[formGroupName],[formArrayName],[ngModelGroup],[formGroup],form:not([ngNoForm]),[ngForm]" }, { kind: "component", type: i1.FormGroupComponent, selector: "c8y-form-group", inputs: ["hasError", "hasWarning", "hasSuccess", "novalidation", "status"] }, { kind: "component", type: i1.MessagesComponent, selector: "c8y-messages", inputs: ["show", "defaults", "helpMessage", "additionalMessages"] }, { kind: "directive", type: i2.FormGroupDirective, selector: "[formGroup]", inputs: ["formGroup"], outputs: ["ngSubmit"], exportAs: ["ngForm"] }, { kind: "directive", type: i2.FormControlName, selector: "[formControlName]", inputs: ["formControlName", "disabled", "ngModel"], outputs: ["ngModelChange"] }, { kind: "ngmodule", type: CommonModule }, { kind: "ngmodule", type: ReactiveFormsModule }, { kind: "pipe", type: i1.C8yTranslatePipe, name: "translate" }, { kind: "pipe", type: i2$1.KeyValuePipe, name: "keyvalue" }], viewProviders: [{ provide: ControlContainer, useExisting: NgForm }] }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: FieldbusItemStatusConfigComponent, decorators: [{
            type: Component,
            args: [{ selector: 'c8y-fieldbus-item-status-config', imports: [CoreModule, CommonModule, C8yTranslatePipe, ReactiveFormsModule], viewProviders: [{ provide: ControlContainer, useExisting: NgForm }], template: "<form [formGroup]=\"formGroup\">\n  <div class=\"d-flex-md row\">\n    <div class=\"col-md-6\">\n      <c8y-form-group style=\"padding-top: var(--c8y-font-size-base)\">\n        <label for=\"fieldbusItem\">{{ 'Fieldbus item' | translate }}</label>\n        <div class=\"c8y-select-wrapper\">\n          <select\n            class=\"form-control\"\n            id=\"fieldbusItem\"\n            formControlName=\"item\"\n          >\n            @for (group of groupedItems; track group.label) {\n              <optgroup [label]=\"group.label | translate\">\n                @for (item of group.items; track item.name) {\n                  <option [ngValue]=\"item\">\n                    {{ item.name }}\n                  </option>\n                }\n              </optgroup>\n            }\n          </select>\n        </div>\n        <c8y-messages\n          [show]=\"formGroup.controls?.item?.touched ? formGroup?.controls?.item?.errors : {}\"\n        ></c8y-messages>\n      </c8y-form-group>\n    </div>\n    <div class=\"col-md-6\">\n      <c8y-form-group style=\"padding-top: var(--c8y-font-size-base)\">\n        <label for=\"resultType\">{{ 'Result type' | translate }}</label>\n        <div class=\"c8y-select-wrapper\">\n          <select\n            class=\"form-control\"\n            id=\"resultType\"\n            formControlName=\"resultType\"\n          >\n            @for (resultType of resultTypes | keyvalue; track resultType.key) {\n              <option [ngValue]=\"resultType.value.value\">\n                {{ resultType.value.label | translate }}\n              </option>\n            }\n          </select>\n        </div>\n      </c8y-form-group>\n    </div>\n  </div>\n</form>\n" }]
        }], propDecorators: { config: [{
                type: Input
            }], asset: [{
                type: Input
            }] } });

export { FieldbusItemStatusConfigComponent };
//# sourceMappingURL=c8y-ngx-components-computed-asset-properties-fieldbus-item-status-config.component-uEdtPWC0.mjs.map
