import * as i0 from '@angular/core';
import { Injectable, Component, NgModule } from '@angular/core';
import * as i1$1 from 'ngx-bootstrap/modal';
import { CdkStep } from '@angular/cdk/stepper';
import { FormGroup } from '@angular/forms';
import { gettext } from '@c8y/ngx-components/gettext';
import * as i3 from '@c8y/ngx-components';
import { ModalComponent, IconDirective, LoadingComponent, C8yStepper, C8yStepperButtons, OperationResultComponent, C8yTranslatePipe, CoreModule, CommonModule } from '@c8y/ngx-components';
import * as i4 from '@ngx-formly/core';
import { FormlyModule } from '@ngx-formly/core';
import { some, uniq, cloneDeep } from 'lodash-es';
import { BehaviorSubject, Subject, of, forkJoin, throwError, defer, from } from 'rxjs';
import { map, catchError, switchMap, takeUntil, mergeMap, shareReplay } from 'rxjs/operators';
import * as i1 from '@c8y/client';
import * as i2 from '@ngx-translate/core';
import { NgIf, NgFor, NgClass, AsyncPipe } from '@angular/common';
import { hookDeviceRegistration } from '@c8y/ngx-components/register-device';

const PRODUCT_EXPERIENCE_ACTILITY_REGISTRATION = {
    EVENT: 'deviceRegistration',
    COMPONENT: 'actility-registration',
    RESULT: { SUCCESS: 'registrationSuccess', FAILURE: 'registrationFailure' }
};

var ActilityErrorName;
(function (ActilityErrorName) {
    ActilityErrorName["NoConnectivityPlansError"] = "NoConnectivityPlansError";
    ActilityErrorName["NoFreeSlotsInConnectivityPlansError"] = "NoFreeSlotsInConnectivityPlansError";
    ActilityErrorName["NoConnectivitySettingsError"] = "NoConnectivitySettingsError";
    ActilityErrorName["ConnectivitySettingsError"] = "ConnectivitySettingsError";
    ActilityErrorName["NoDeviceProfilesError"] = "NoDeviceProfilesError";
    ActilityErrorName["DeviceProfilesFetchError"] = "DeviceProfilesFetchError";
    ActilityErrorName["NoDeviceProtocolsError"] = "NoDeviceProtocolsError";
    ActilityErrorName["DeviceProtocolsFetchError"] = "DeviceProtocolsFetchError";
    ActilityErrorName["RegistrationError"] = "RegistrationError";
})(ActilityErrorName || (ActilityErrorName = {}));
class ActilityDeviceRegistrationService {
    constructor(inventoryService, client, translateService, applicationService, optionsService, appState) {
        this.inventoryService = inventoryService;
        this.client = client;
        this.translateService = translateService;
        this.applicationService = applicationService;
        this.optionsService = optionsService;
        this.appState = appState;
        this.baseUrl = '/service/actility';
        this.registrationUrl = `${this.baseUrl}/newDeviceRequest`;
        this.connectivityPlansUrl = `${this.baseUrl}/connectivityPlans`;
        this.deviceProfilesUrl = `${this.baseUrl}/deviceProfiles`;
        this.headers = {
            'Content-Type': 'application/json'
        };
    }
    async getConnections() {
        const options = {
            method: 'GET',
            headers: this.headers
        };
        const res = await this.client.fetch(`${this.baseUrl}/lns-connection`, options);
        const data = await res.json();
        if (res.status === 200) {
            if (data.length === 0) {
                await this.throwNoConnectivitySettingsError();
            }
        }
        else {
            await this.throwConnectivitySettingsError(data);
        }
        return { res, data };
    }
    /**
     * Gets connectivity plans from LoRa platform.
     * @param connectionName The name of connection for which connectivity plans will be retrieved
     * @returns The result list with connectivity plans, or throws an error with exception.
     */
    async getConnectivityPlans(connectionName) {
        const options = {
            method: 'GET',
            headers: this.headers,
            params: {
                actilityConnectionName: connectionName
            }
        };
        const res = await this.client.fetch(this.connectivityPlansUrl, options);
        const data = await res.json();
        if (res.status === 200) {
            if (data.length === 0) {
                this.throwNoConnectivityPlansError();
            }
            else {
                if (!this.hasAvailableConnections(data)) {
                    this.throwNoFreeSlotsInConnectivityPlansError();
                }
            }
        }
        else {
            await this.throwConnectivitySettingsError(data);
        }
        return { res, data };
    }
    /**
     * Gets the device profiles from LoRa platform.
     * @param connectionName The name of connection for which device profiles will be retrieved
     * @returns The result list with device profiles, or throws an error with exception.
     */
    async getDeviceProfiles(connectionName) {
        const options = {
            method: 'GET',
            headers: this.headers,
            params: {
                actilityConnectionName: connectionName
            }
        };
        const res = await this.client.fetch(this.deviceProfilesUrl, options);
        const data = await res.json();
        if (res.status === 200) {
            if (data.length === 0) {
                this.throwNoDeviceProfilesError();
            }
        }
        else {
            this.throwDeviceProfilesFetchError();
        }
        return { res, data };
    }
    /**
     * Gets the device protocols
     */
    async getDeviceProtocols(filter = { withTotalPages: true }) {
        const query = {
            __filter: {
                __and: [
                    { __has: 'c8y_IsDeviceType' },
                    {
                        type: { __in: ['c8y_ActilityDeviceType', 'c8y_LoraDeviceType', 'c8y_LpwanDeviceType'] }
                    }
                ]
            },
            __orderby: [{ name: 1 }]
        };
        const deviceProtocolsList = await this.inventoryService.listQuery(query, filter);
        const { res, data } = deviceProtocolsList;
        if (res.status === 200) {
            if (data.length === 0) {
                this.throwNoDeviceProtocolsError();
            }
        }
        else {
            this.throwDeviceProtocolsFetchError();
        }
        return deviceProtocolsList;
    }
    /**
     * Creates device registration
     */
    async register(registration) {
        const options = {
            method: 'POST',
            headers: this.headers,
            body: JSON.stringify(registration)
        };
        const res = await this.client.fetch(this.registrationUrl, options);
        const data = await res.json();
        if (res.status !== 201) {
            this.throwRegistrationError(data);
        }
        return { res, data };
    }
    /**
     * checks if used connections is less then granted connections
     */
    hasAvailableConnections(connectivityPlans) {
        return some(connectivityPlans, plan => parseInt(plan.grantedConnections, 10) > parseInt(plan.usedConnections, 10));
    }
    async throwNoConnectivitySettingsError() {
        const error = new Error();
        error.name = ActilityErrorName.NoConnectivitySettingsError;
        if (await this.appState.isApplicationAvailable('administration')) {
            error.message = this.translateService.instant(gettext(`Could not get connectivity plans from the LoRa platform. Verify the ThingPark credentials in the Administration application under <a href="{{ link }}">Settings</a>.`), {
                link: '/apps/administration/index.html#/connectivitySettings/multiple_lns_connectors_actility'
            });
        }
        else {
            error.message = gettext('Could not get connectivity plans from the LoRa platform. Please contact the administrator.');
        }
        throw error;
    }
    throwConnectivitySettingsError(data) {
        const error = new Error();
        error.name = ActilityErrorName.ConnectivitySettingsError;
        error.message = data.message;
        throw error;
    }
    throwNoConnectivityPlansError() {
        const error = new Error();
        error.name = ActilityErrorName.NoConnectivityPlansError;
        error.message = gettext('No connectivity plans found. New connectivity plans must be created via the LoRa platform.');
        throw error;
    }
    throwNoFreeSlotsInConnectivityPlansError() {
        const companyName = this.optionsService.get('companyName', 'Cumulocity IoT');
        const error = new Error();
        error.name = ActilityErrorName.NoFreeSlotsInConnectivityPlansError;
        error.message = this.translateService.instant(gettext(`No connectivity plans with free slots available. Please contact ThingPark on the device quota limits for your connectivity plans or remove unused devices from ThingPark and retry registering the device in the {{companyName}} platform.`), {
            companyName
        });
        throw error;
    }
    throwDeviceProfilesFetchError() {
        const error = new Error();
        error.name = ActilityErrorName.DeviceProfilesFetchError;
        error.message = gettext('Could not load device profiles from the LoRa platform.');
        throw error;
    }
    throwNoDeviceProfilesError() {
        const error = new Error();
        error.name = ActilityErrorName.NoDeviceProfilesError;
        error.message = gettext('No device profiles found. Create a new device profile via the LoRa platform.');
        throw error;
    }
    throwDeviceProtocolsFetchError() {
        const error = new Error();
        error.name = ActilityErrorName.DeviceProtocolsFetchError;
        error.message = gettext('Could not load device protocols.');
        throw error;
    }
    throwNoDeviceProtocolsError() {
        const error = new Error();
        error.name = ActilityErrorName.NoDeviceProtocolsError;
        error.message = this.translateService.instant(gettext(`No device protocols configured. Create a LoRa device protocol in <a href="{{ link }}">Device protocols</a>.`), {
            link: '/apps/devicemanagement/#/deviceprotocols'
        });
        throw error;
    }
    throwRegistrationError(data) {
        const error = new Error();
        error.name = ActilityErrorName.RegistrationError;
        error.message = data.message;
        throw error;
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.3.25", ngImport: i0, type: ActilityDeviceRegistrationService, deps: [{ token: i1.InventoryService }, { token: i1.FetchClient }, { token: i2.TranslateService }, { token: i1.ApplicationService }, { token: i3.OptionsService }, { token: i3.AppStateService }], target: i0.ɵɵFactoryTarget.Injectable }); }
    static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "20.3.25", ngImport: i0, type: ActilityDeviceRegistrationService, providedIn: 'root' }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.25", ngImport: i0, type: ActilityDeviceRegistrationService, decorators: [{
            type: Injectable,
            args: [{ providedIn: 'root' }]
        }], ctorParameters: () => [{ type: i1.InventoryService }, { type: i1.FetchClient }, { type: i2.TranslateService }, { type: i1.ApplicationService }, { type: i3.OptionsService }, { type: i3.AppStateService }] });

class ActilityDeviceRegistrationComponent {
    constructor(bsModalRef, registrationService, gainsightService) {
        this.bsModalRef = bsModalRef;
        this.registrationService = registrationService;
        this.gainsightService = gainsightService;
        this.registrationStepLabels = {
            next: gettext('Register')
        };
        this.finalStepLabels = {
            custom: gettext('Close')
        };
        this.state = 'loadPending';
        this.errors$ = new BehaviorSubject([]);
        this.errorMessages$ = this.errors$.pipe(map(errors => errors.map(error => error.message)), map(messages => uniq(messages)));
        this.connections$ = this.getConnections$();
        this.deviceProtocols$ = this.getDeviceProtocols$();
        this.unsubscribe$ = new Subject();
        this.load$ = this.connections$.pipe(catchError((error) => of(error)), switchMap(connections => {
            if (connections instanceof Error &&
                connections.name === ActilityErrorName.NoConnectivitySettingsError) {
                return of([connections]);
            }
            return forkJoin([
                of(connections),
                this.deviceProtocols$.pipe(catchError((error) => of(error)))
            ]);
        }), map(results => results.filter(result => result instanceof Error)), switchMap(errors => (errors.length === 0 ? of([]) : throwError(errors))));
        this.form = new FormGroup({});
        this.model = {};
        // Formly schema definition to render actility device registration form
        this.fields = [
            {
                key: 'connection',
                type: 'typeahead',
                templateOptions: {
                    label: gettext('Connection'),
                    required: true,
                    c8yForOptions: this.connections$,
                    displayProperty: 'name',
                    valueProperties: ['name']
                }
            },
            {
                key: 'deviceProfile',
                type: 'typeahead',
                templateOptions: {
                    label: gettext('Device profile'),
                    required: true,
                    displayProperty: 'name',
                    placeholder: 'IWM-LR3',
                    valueProperties: ['id', 'name', 'typeMAC']
                },
                hooks: {
                    onInit: field => {
                        const connectionControl = field.form.get('connection');
                        connectionControl.valueChanges
                            .pipe(takeUntil(this.unsubscribe$), mergeMap(({ name }) => this.getDeviceProfiles$(name)))
                            .subscribe(profiles => {
                            field.templateOptions.c8yForOptions = of(profiles);
                            field.formControl.setValue(null);
                        }, error => {
                            field.form.get('deviceProfile').setErrors({ deviceProfile: true });
                            field.validators.deviceProfile.message = error.message;
                        });
                    }
                },
                validators: {
                    deviceProfile: {
                        expression: (control) => {
                            return control.status === 'VALID';
                        },
                        message: () => ''
                    }
                }
            },
            {
                key: 'deviceType',
                type: 'typeahead',
                templateOptions: {
                    label: gettext('Device protocol'),
                    required: true,
                    c8yForOptions: this.deviceProtocols$,
                    displayProperty: 'name',
                    valueProperties: ['id', 'name']
                }
            },
            {
                key: 'devEUI',
                type: 'input',
                templateOptions: {
                    placeholder: '0018A20000000004',
                    label: gettext('Device EUI'),
                    required: true,
                    pattern: '^([a-fA-F0-9]{16})$'
                },
                validation: {
                    messages: {
                        pattern: gettext('Must be a valid 16 digit hexadecimal number.')
                    }
                }
            },
            {
                key: 'applicationEUI',
                type: 'input',
                templateOptions: {
                    placeholder: '70B3D53260000003',
                    label: gettext('Application EUI'),
                    required: true,
                    pattern: '^([a-fA-F0-9]{16})$'
                },
                validation: {
                    messages: {
                        pattern: gettext('Must be a valid 16 digit hexadecimal number.')
                    }
                }
            },
            {
                key: 'applicationKey',
                type: 'input',
                templateOptions: {
                    label: gettext('Application key'),
                    placeholder: '258DB54023EA74F0D55085F7351737D0',
                    required: true,
                    pattern: '^([a-fA-F0-9]{32})$'
                },
                validation: {
                    messages: {
                        pattern: gettext('Must be a valid 32 digit hexadecimal number.')
                    }
                }
            },
            {
                key: 'connectivityPlan',
                type: 'typeahead',
                templateOptions: {
                    label: gettext('Connectivity plan'),
                    description: gettext('Only connectivity plans with free slots are displayed'),
                    required: true,
                    placeholder: 'Dev-ope testing CP',
                    displayProperty: 'name',
                    valueProperties: ['id', 'ref', 'name', 'grantedConnections', 'usedConnections']
                },
                hooks: {
                    onInit: field => {
                        const connectionControl = field.form.get('connection');
                        connectionControl.valueChanges
                            .pipe(takeUntil(this.unsubscribe$), mergeMap(({ name }) => this.getConnectivityPlans$(name)))
                            .subscribe(profiles => {
                            field.templateOptions.c8yForOptions = of(profiles);
                            field.formControl.setValue(null);
                        }, error => {
                            field.form.get('connectivityPlan').setErrors({ connectivityPlan: true });
                            field.validators.connectivityPlan.message = error.message;
                        });
                    }
                },
                validators: {
                    connectivityPlan: {
                        expression: (control) => {
                            return control.status === 'VALID';
                        },
                        message: () => ''
                    }
                }
            }
        ];
        this.load$.subscribe(() => {
            this.state = 'loadSuccess';
        }, errors => {
            this.state = 'loadError';
            this.errors$.next(errors);
        });
    }
    getConnectivityPlans$(name) {
        return defer(() => from(this.registrationService.getConnectivityPlans(name))).pipe(shareReplay(1));
    }
    getDeviceProfiles$(name) {
        return defer(() => from(this.registrationService.getDeviceProfiles(name))).pipe(shareReplay(1));
    }
    getDeviceProtocols$() {
        return defer(() => from(this.registrationService.getDeviceProtocols())).pipe(shareReplay(1));
    }
    getConnections$() {
        return defer(() => from(this.registrationService.getConnections())).pipe(shareReplay(1));
    }
    async register(event) {
        event.stepper.next();
        this.state = 'registrationPending';
        try {
            const actilityDevice = this.getActilityDeviceToSend();
            await this.registrationService.register(actilityDevice);
            this.state = 'registrationSuccess';
            this.gainsightService.triggerEvent(PRODUCT_EXPERIENCE_ACTILITY_REGISTRATION.EVENT, {
                result: PRODUCT_EXPERIENCE_ACTILITY_REGISTRATION.RESULT.SUCCESS,
                component: PRODUCT_EXPERIENCE_ACTILITY_REGISTRATION.COMPONENT
            });
        }
        catch (error) {
            this.state = 'registrationError';
            this.gainsightService.triggerEvent(PRODUCT_EXPERIENCE_ACTILITY_REGISTRATION.EVENT, {
                result: PRODUCT_EXPERIENCE_ACTILITY_REGISTRATION.RESULT.FAILURE,
                component: PRODUCT_EXPERIENCE_ACTILITY_REGISTRATION.COMPONENT
            });
            this.errors$.next([error]);
        }
    }
    getActilityDeviceToSend() {
        const actilityDevice = cloneDeep(this.model);
        actilityDevice.lnsConnectionName = this.model.connection.name;
        delete actilityDevice.connection;
        return actilityDevice;
    }
    ngOnDestroy() {
        this.unsubscribe$.next();
        this.unsubscribe$.complete();
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.3.25", ngImport: i0, type: ActilityDeviceRegistrationComponent, deps: [{ token: i1$1.BsModalRef }, { token: ActilityDeviceRegistrationService }, { token: i3.GainsightService }], target: i0.ɵɵFactoryTarget.Component }); }
    static { this.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "20.3.25", type: ActilityDeviceRegistrationComponent, isStandalone: true, selector: "c8y-actility-registration", ngImport: i0, template: "<c8y-modal\n  [title]=\"'Actility LoRa registration' | translate\"\n  [headerClasses]=\"'dialog-header'\"\n  [customFooter]=\"true\"\n>\n  <ng-container c8y-modal-title>\n    <span [c8yIcon]=\"'c8y-device-connect'\"></span>\n  </ng-container>\n\n  <ng-container *ngIf=\"state === 'loadPending'; else registrationForm\">\n    <div class=\"p-16 text-center\">\n      <c8y-loading></c8y-loading>\n    </div>\n  </ng-container>\n\n  <!--Formly schema is rendered-->\n  <ng-template #registrationForm>\n    <c8y-stepper\n      [hideStepProgress]=\"true\"\n      c8y-modal-body\n      linear\n      *ngIf=\"(errorMessages$ | async).length === 0; else errorMessagesPresent\"\n    >\n      <cdk-step [stepControl]=\"form\">\n        <div class=\"p-b-16\">\n          <p class=\"modal-subtitle sticky-top\">\n            {{ 'Register a single Actility device' | translate }}\n          </p>\n          <formly-form\n            class=\"formly-group-array-cols d-block p-l-24 p-r-24 p-t-16\"\n            [form]=\"form\"\n            [fields]=\"fields\"\n            [model]=\"model\"\n          ></formly-form>\n        </div>\n\n        <c8y-stepper-buttons\n          class=\"sticky-bottom d-block p-t-16 p-b-16 separator-top bg-level-0\"\n          [labels]=\"registrationStepLabels\"\n          (onNext)=\"register($event)\"\n          (onCancel)=\"bsModalRef.hide()\"\n          [showButtons]=\"{ cancel: true, next: true }\"\n          [pending]=\"state === 'registrationPending'\"\n          [disabled]=\"!form?.valid\"\n        ></c8y-stepper-buttons>\n      </cdk-step>\n      <cdk-step state=\"final\">\n        <!--success scenario-->\n        <div\n          class=\"p-16 text-center\"\n          *ngIf=\"state === 'registrationPending'\"\n        >\n          <c8y-loading></c8y-loading>\n        </div>\n        <div class=\"m-24\">\n          <c8y-operation-result\n            class=\"lead m-b-0\"\n            type=\"success\"\n            *ngIf=\"state === 'registrationSuccess'\"\n            text=\"{{ 'Device registered' | translate }}\"\n            [size]=\"84\"\n            [vertical]=\"true\"\n          ></c8y-operation-result>\n        </div>\n        <c8y-stepper-buttons\n          class=\"sticky-bottom d-block p-t-16 p-b-16 separator-top bg-level-0\"\n          (onCustom)=\"bsModalRef.hide()\"\n          [showButtons]=\"{ custom: true }\"\n          [labels]=\"finalStepLabels\"\n        ></c8y-stepper-buttons>\n      </cdk-step>\n    </c8y-stepper>\n  </ng-template>\n\n  <!--Failure scenario-->\n  <ng-template #errorMessagesPresent>\n    <div class=\"m-24\">\n      <c8y-operation-result\n        class=\"lead\"\n        type=\"error\"\n        *ngIf=\"state === 'registrationError'\"\n        text=\"{{ 'Failed to register' | translate }}\"\n        [size]=\"84\"\n        [vertical]=\"true\"\n      ></c8y-operation-result>\n      <div\n        class=\"m-b-8\"\n        *ngFor=\"let msg of errorMessages$ | async\"\n        data-cy=\"actility-device-registration.component--registration-error\"\n        [ngClass]=\"{\n          'text-center': state === 'registrationError',\n          'alert alert-danger': state === 'loadError'\n        }\"\n      >\n        <span [innerHTML]=\"msg | translate\"></span>\n      </div>\n    </div>\n    <div class=\"modal-footer\">\n      <button\n        class=\"btn btn-default\"\n        title=\"{{ 'Close' | translate }}\"\n        type=\"button\"\n        (click)=\"bsModalRef.hide()\"\n      >\n        {{ 'Close' | translate }}\n      </button>\n    </div>\n  </ng-template>\n</c8y-modal>\n", dependencies: [{ kind: "component", type: ModalComponent, selector: "c8y-modal", inputs: ["disabled", "close", "dismiss", "title", "body", "customFooter", "headerClasses", "labels"], outputs: ["onDismiss", "onClose"] }, { kind: "directive", type: IconDirective, selector: "[c8yIcon]", inputs: ["c8yIcon"] }, { kind: "directive", type: NgIf, selector: "[ngIf]", inputs: ["ngIf", "ngIfThen", "ngIfElse"] }, { kind: "component", type: LoadingComponent, selector: "c8y-loading", inputs: ["layout", "progress", "message"] }, { kind: "component", type: C8yStepper, selector: "c8y-stepper", inputs: ["disableDefaultIcons", "disableProgressButtons", "customClasses", "hideStepProgress", "useStepLabelsAsTitlesOnly"], outputs: ["onStepChange"] }, { kind: "component", type: CdkStep, selector: "cdk-step", inputs: ["stepControl", "label", "errorMessage", "aria-label", "aria-labelledby", "state", "editable", "optional", "completed", "hasError"], outputs: ["interacted"], exportAs: ["cdkStep"] }, { kind: "ngmodule", type: FormlyModule }, { kind: "component", type: i4.FormlyForm, selector: "formly-form", inputs: ["form", "model", "fields", "options"], outputs: ["modelChange"] }, { kind: "component", type: C8yStepperButtons, selector: "c8y-stepper-buttons", inputs: ["labels", "pending", "disabled", "showButtons"], outputs: ["onCancel", "onNext", "onBack", "onCustom"] }, { kind: "component", type: OperationResultComponent, selector: "c8y-operation-result", inputs: ["text", "vertical", "size", "type"] }, { kind: "directive", type: NgFor, selector: "[ngFor][ngForOf]", inputs: ["ngForOf", "ngForTrackBy", "ngForTemplate"] }, { kind: "directive", type: NgClass, selector: "[ngClass]", inputs: ["class", "ngClass"] }, { kind: "pipe", type: C8yTranslatePipe, name: "translate" }, { kind: "pipe", type: AsyncPipe, name: "async" }] }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.25", ngImport: i0, type: ActilityDeviceRegistrationComponent, decorators: [{
            type: Component,
            args: [{ selector: 'c8y-actility-registration', imports: [
                        ModalComponent,
                        IconDirective,
                        NgIf,
                        LoadingComponent,
                        C8yStepper,
                        CdkStep,
                        FormlyModule,
                        C8yStepperButtons,
                        OperationResultComponent,
                        NgFor,
                        NgClass,
                        C8yTranslatePipe,
                        AsyncPipe
                    ], template: "<c8y-modal\n  [title]=\"'Actility LoRa registration' | translate\"\n  [headerClasses]=\"'dialog-header'\"\n  [customFooter]=\"true\"\n>\n  <ng-container c8y-modal-title>\n    <span [c8yIcon]=\"'c8y-device-connect'\"></span>\n  </ng-container>\n\n  <ng-container *ngIf=\"state === 'loadPending'; else registrationForm\">\n    <div class=\"p-16 text-center\">\n      <c8y-loading></c8y-loading>\n    </div>\n  </ng-container>\n\n  <!--Formly schema is rendered-->\n  <ng-template #registrationForm>\n    <c8y-stepper\n      [hideStepProgress]=\"true\"\n      c8y-modal-body\n      linear\n      *ngIf=\"(errorMessages$ | async).length === 0; else errorMessagesPresent\"\n    >\n      <cdk-step [stepControl]=\"form\">\n        <div class=\"p-b-16\">\n          <p class=\"modal-subtitle sticky-top\">\n            {{ 'Register a single Actility device' | translate }}\n          </p>\n          <formly-form\n            class=\"formly-group-array-cols d-block p-l-24 p-r-24 p-t-16\"\n            [form]=\"form\"\n            [fields]=\"fields\"\n            [model]=\"model\"\n          ></formly-form>\n        </div>\n\n        <c8y-stepper-buttons\n          class=\"sticky-bottom d-block p-t-16 p-b-16 separator-top bg-level-0\"\n          [labels]=\"registrationStepLabels\"\n          (onNext)=\"register($event)\"\n          (onCancel)=\"bsModalRef.hide()\"\n          [showButtons]=\"{ cancel: true, next: true }\"\n          [pending]=\"state === 'registrationPending'\"\n          [disabled]=\"!form?.valid\"\n        ></c8y-stepper-buttons>\n      </cdk-step>\n      <cdk-step state=\"final\">\n        <!--success scenario-->\n        <div\n          class=\"p-16 text-center\"\n          *ngIf=\"state === 'registrationPending'\"\n        >\n          <c8y-loading></c8y-loading>\n        </div>\n        <div class=\"m-24\">\n          <c8y-operation-result\n            class=\"lead m-b-0\"\n            type=\"success\"\n            *ngIf=\"state === 'registrationSuccess'\"\n            text=\"{{ 'Device registered' | translate }}\"\n            [size]=\"84\"\n            [vertical]=\"true\"\n          ></c8y-operation-result>\n        </div>\n        <c8y-stepper-buttons\n          class=\"sticky-bottom d-block p-t-16 p-b-16 separator-top bg-level-0\"\n          (onCustom)=\"bsModalRef.hide()\"\n          [showButtons]=\"{ custom: true }\"\n          [labels]=\"finalStepLabels\"\n        ></c8y-stepper-buttons>\n      </cdk-step>\n    </c8y-stepper>\n  </ng-template>\n\n  <!--Failure scenario-->\n  <ng-template #errorMessagesPresent>\n    <div class=\"m-24\">\n      <c8y-operation-result\n        class=\"lead\"\n        type=\"error\"\n        *ngIf=\"state === 'registrationError'\"\n        text=\"{{ 'Failed to register' | translate }}\"\n        [size]=\"84\"\n        [vertical]=\"true\"\n      ></c8y-operation-result>\n      <div\n        class=\"m-b-8\"\n        *ngFor=\"let msg of errorMessages$ | async\"\n        data-cy=\"actility-device-registration.component--registration-error\"\n        [ngClass]=\"{\n          'text-center': state === 'registrationError',\n          'alert alert-danger': state === 'loadError'\n        }\"\n      >\n        <span [innerHTML]=\"msg | translate\"></span>\n      </div>\n    </div>\n    <div class=\"modal-footer\">\n      <button\n        class=\"btn btn-default\"\n        title=\"{{ 'Close' | translate }}\"\n        type=\"button\"\n        (click)=\"bsModalRef.hide()\"\n      >\n        {{ 'Close' | translate }}\n      </button>\n    </div>\n  </ng-template>\n</c8y-modal>\n" }]
        }], ctorParameters: () => [{ type: i1$1.BsModalRef }, { type: ActilityDeviceRegistrationService }, { type: i3.GainsightService }] });

class ActilityDeviceRegistrationButtonComponent {
    constructor(modalService) {
        this.modalService = modalService;
    }
    open() {
        this.modalService.show(ActilityDeviceRegistrationComponent, {
            class: 'modal-sm',
            ariaDescribedby: 'modal-body',
            ariaLabelledBy: 'modal-title',
            ignoreBackdropClick: true
        });
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.3.25", ngImport: i0, type: ActilityDeviceRegistrationButtonComponent, deps: [{ token: i1$1.BsModalService }], target: i0.ɵɵFactoryTarget.Component }); }
    static { this.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "20.3.25", type: ActilityDeviceRegistrationButtonComponent, isStandalone: true, selector: "c8y-actility-registration-button", ngImport: i0, template: "<button title=\"{{ 'Actility LoRa' | translate }}\" type=\"button\" (click)=\"open()\">\n  <i c8yIcon=\"c8y-device-connect\"></i>\n  {{ 'Actility LoRa' | translate }}\n</button>\n", dependencies: [{ kind: "directive", type: IconDirective, selector: "[c8yIcon]", inputs: ["c8yIcon"] }, { kind: "pipe", type: C8yTranslatePipe, name: "translate" }] }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.25", ngImport: i0, type: ActilityDeviceRegistrationButtonComponent, decorators: [{
            type: Component,
            args: [{ selector: 'c8y-actility-registration-button', imports: [IconDirective, C8yTranslatePipe], template: "<button title=\"{{ 'Actility LoRa' | translate }}\" type=\"button\" (click)=\"open()\">\n  <i c8yIcon=\"c8y-device-connect\"></i>\n  {{ 'Actility LoRa' | translate }}\n</button>\n" }]
        }], ctorParameters: () => [{ type: i1$1.BsModalService }] });

class ActilityDeviceRegistrationFactory {
    constructor(tenantService) {
        this.tenantService = tenantService;
    }
    get() {
        const actions = [];
        if (this.tenantService.isMicroserviceSubscribedInCurrentTenant('actility')) {
            actions.push({
                template: ActilityDeviceRegistrationButtonComponent,
                priority: 99,
                category: 'single'
            });
        }
        return actions;
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.3.25", ngImport: i0, type: ActilityDeviceRegistrationFactory, deps: [{ token: i3.TenantUiService }], target: i0.ɵɵFactoryTarget.Injectable }); }
    static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "20.3.25", ngImport: i0, type: ActilityDeviceRegistrationFactory, providedIn: 'root' }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.25", ngImport: i0, type: ActilityDeviceRegistrationFactory, decorators: [{
            type: Injectable,
            args: [{
                    providedIn: 'root'
                }]
        }], ctorParameters: () => [{ type: i3.TenantUiService }] });

class ActilityDeviceRegistrationModule {
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.3.25", ngImport: i0, type: ActilityDeviceRegistrationModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule }); }
    static { this.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "20.3.25", ngImport: i0, type: ActilityDeviceRegistrationModule, imports: [CoreModule,
            CommonModule,
            ActilityDeviceRegistrationButtonComponent,
            ActilityDeviceRegistrationComponent] }); }
    static { this.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "20.3.25", ngImport: i0, type: ActilityDeviceRegistrationModule, providers: [
            ActilityDeviceRegistrationService,
            hookDeviceRegistration(ActilityDeviceRegistrationFactory)
        ], imports: [CoreModule,
            CommonModule,
            ActilityDeviceRegistrationComponent] }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.25", ngImport: i0, type: ActilityDeviceRegistrationModule, decorators: [{
            type: NgModule,
            args: [{
                    imports: [
                        CoreModule,
                        CommonModule,
                        ActilityDeviceRegistrationButtonComponent,
                        ActilityDeviceRegistrationComponent
                    ],
                    providers: [
                        ActilityDeviceRegistrationService,
                        hookDeviceRegistration(ActilityDeviceRegistrationFactory)
                    ]
                }]
        }] });

/**
 * Generated bundle index. Do not edit.
 */

export { ActilityDeviceRegistrationButtonComponent, ActilityDeviceRegistrationComponent, ActilityDeviceRegistrationFactory, ActilityDeviceRegistrationModule };
//# sourceMappingURL=c8y-ngx-components-actility-device-registration.mjs.map
