import { Component, ViewChild } from '@angular/core';
import { FormGroup } from '@angular/forms';
import { DeviceRegistrationBulkService } from '@c8y/client';
import { C8yJSONSchema, C8yStepper, FeatureCacheService, GainsightService, gettext } from '@c8y/ngx-components';
import { saveAs } from 'file-saver';
import { BsModalRef } from 'ngx-bootstrap/modal';
import { PRODUCT_EXPERIENCE_BASE_REGISTRATION } from '../extensible/base-device-registration.model';
import { RegisterDeviceService } from '../register-device.service';
import { TranslateService } from '@ngx-translate/core';
import * as i0 from "@angular/core";
import * as i1 from "@c8y/ngx-components";
import * as i2 from "@c8y/client";
import * as i3 from "../register-device.service";
import * as i4 from "ngx-bootstrap/modal";
import * as i5 from "@ngx-translate/core";
import * as i6 from "@angular/common";
import * as i7 from "@angular/cdk/stepper";
import * as i8 from "@ngx-formly/core";
const registerDeviceBulkSchema = {
    $schema: 'https://json-schema.org/draft/2019-09/schema',
    type: 'object',
    properties: {
        csvBulkFile: {
            type: 'array',
            title: gettext('CSV file upload'),
            description: gettext('You can use file upload component to let users send files. This input accepts only a single CSV file.'),
            contentMediaType: 'csv'
        }
    },
    required: ['csvBulkFile'],
    additionalProperties: false
};
const simpleCsvHeaders = ['ID', 'PATH'];
const csvHeaders = [
    'ID',
    'TYPE',
    'NAME',
    'ICCID',
    'IDTYPE',
    'PATH',
    'SHELL',
    'AUTH_TYPE'
];
const fullCsvHeaders = [...csvHeaders, 'CREDENTIALS'];
export const ESTCsvHeaders = [...csvHeaders, 'ENROLLMENT_OTP'];
export class BulkDeviceRegistrationModalComponent {
    constructor(jsonschema, deviceRegistrationService, registerDeviceService, bsModalRef, gainsightService, featureCacheService, translateService) {
        this.jsonschema = jsonschema;
        this.deviceRegistrationService = deviceRegistrationService;
        this.registerDeviceService = registerDeviceService;
        this.bsModalRef = bsModalRef;
        this.gainsightService = gainsightService;
        this.featureCacheService = featureCacheService;
        this.translateService = translateService;
        this.form = new FormGroup({});
        this.model = {};
        this.certificateAuthorityFeatureEnabled = this.featureCacheService.getFeatureState('certificate-authority');
    }
    ngOnInit() {
        this.template = [this.jsonschema.toFieldConfig(registerDeviceBulkSchema)];
    }
    upload() {
        this.pending = true;
        const file = this.getFile(this.model);
        this.deviceRegistrationService
            .create(file)
            .then(({ res, data }) => {
            if (res.status < 400) {
                this.result = data;
                this.success = data.numberOfFailed === 0 && data.numberOfSuccessful === data.numberOfAll;
                this.message = this.success
                    ? gettext('Device registration created.')
                    : (this.message = gettext('Device registration failed.'));
                if (this.success) {
                    this.gainsightService.triggerEvent(PRODUCT_EXPERIENCE_BASE_REGISTRATION.EVENT, {
                        result: PRODUCT_EXPERIENCE_BASE_REGISTRATION.RESULT.SUCCESS,
                        component: PRODUCT_EXPERIENCE_BASE_REGISTRATION.COMPONENT.BULK
                    });
                }
                else {
                    this.gainsightService.triggerEvent(PRODUCT_EXPERIENCE_BASE_REGISTRATION.EVENT, {
                        result: PRODUCT_EXPERIENCE_BASE_REGISTRATION.RESULT.FAILURE,
                        component: PRODUCT_EXPERIENCE_BASE_REGISTRATION.COMPONENT.BULK
                    });
                }
            }
            else {
                this.failedResult = data;
                this.message = gettext('Device registration failed.');
                this.gainsightService.triggerEvent(PRODUCT_EXPERIENCE_BASE_REGISTRATION.EVENT, {
                    result: PRODUCT_EXPERIENCE_BASE_REGISTRATION.RESULT.FAILURE,
                    component: PRODUCT_EXPERIENCE_BASE_REGISTRATION.COMPONENT.BULK
                });
            }
            this.model = {};
            this.pending = false;
            this.stepper.next();
        })
            .catch(() => {
            this.message = gettext('Error occurred while processing the uploaded file.');
            this.pending = false;
            this.stepper.next();
        });
    }
    downloadSimple() {
        return this.download(simpleCsvHeaders, gettext('Simple bulk registration - template.csv'));
    }
    downloadFull() {
        return this.download(fullCsvHeaders, gettext('Full bulk registration - template.csv'));
    }
    downloadEst() {
        return this.download(ESTCsvHeaders, gettext('EST registration - template.csv'));
    }
    download(headers, fileName) {
        const headerRaw = headers.map(header => `"${header}"`).join(';');
        const binaryFile = new Blob([headerRaw], { type: 'text/csv' });
        saveAs(binaryFile, this.translateService.instant(fileName));
    }
    complete() {
        this.registerDeviceService.list();
        this.bsModalRef.hide();
    }
    cancel() {
        this.bsModalRef.hide();
    }
    getFile(model) {
        const csvBulkFile = model?.csvBulkFile;
        return csvBulkFile ? csvBulkFile[0]?.file : undefined;
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "18.2.13", ngImport: i0, type: BulkDeviceRegistrationModalComponent, deps: [{ token: i1.C8yJSONSchema }, { token: i2.DeviceRegistrationBulkService }, { token: i3.RegisterDeviceService }, { token: i4.BsModalRef }, { token: i1.GainsightService }, { token: i1.FeatureCacheService }, { token: i5.TranslateService }], target: i0.ɵɵFactoryTarget.Component }); }
    static { this.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "18.2.13", type: BulkDeviceRegistrationModalComponent, selector: "bulk-device-registration", viewQueries: [{ propertyName: "stepper", first: true, predicate: C8yStepper, descendants: true, static: true }], ngImport: i0, template: "<c8y-modal\n  [title]=\"'Bulk device registration' | translate\"\n  [headerClasses]=\"'dialog-header'\"\n  [customFooter]=\"true\"\n>\n  <ng-container c8y-modal-title>\n    <i c8yIcon=\"upload\"></i>\n  </ng-container>\n\n  <c8y-stepper [hideStepProgress]=\"true\" linear id=\"modal-body\">\n    <cdk-step>\n      <p class=\"modal-subtitle sticky-top\" translate>Register devices in bulk</p>\n\n      <c8y-form-group class=\"d-block p-24 p-t-16 p-b-0 m-b-0\">\n        <formly-form [form]=\"form\" [fields]=\"template\" [model]=\"model\"></formly-form>\n      </c8y-form-group>\n\n      <div class=\"p-24 m-t-0 bg-level-1\">\n          <div class=\"bg-gray-white separator-bottom p-t-16 p-b-16 p-l-24 p-r-24\">\n            <div>\n              <p class=\"m-b-8 text-medium\">\n                <strong translate>Simple registration</strong>\n              </p>\n              <small class=\"text-muted\" translate>\n                Creates all registration requests at once, then each one needs to go through regular\n                acceptance process.\n              </small>\n            </div>\n            <div class=\"m-b-16 m-t-16\">\n              <a\n                title=\"{{ 'Download template' | translate }}\"\n                class=\"btn btn-default btn-sm\"\n                target=\"_self\"\n                (click)=\"downloadSimple()\"\n              >\n                <i c8yIcon=\"download\" translate></i>\n                {{ 'Download template' | translate }}\n              </a>\n            </div>\n          </div>\n          <div class=\"bg-gray-white separator-bottom p-t-16 p-b-16 p-l-24 p-r-24\">\n            <div>\n              <p class=\"m-b-8 text-medium\">\n                <strong translate>Full registration</strong>\n              </p>\n              <small class=\"text-muted\" translate>\n                Creates all device credentials and devices using provided list of property values.\n                Devices can start communicating with the platform immediately.\n              </small>\n            </div>\n            <div class=\"m-b-16 m-t-16\">\n              <a\n                title=\"{{ 'Download template' | translate }}\"\n                class=\"btn btn-default btn-sm\"\n                target=\"_self\"\n                (click)=\"downloadFull()\"\n              >\n                <i c8yIcon=\"download\" translate></i>\n                {{ 'Download template' | translate }}\n              </a>\n            </div>\n          </div>\n          <div class=\"bg-gray-white separator-bottom p-t-16 p-b-16 p-l-24 p-r-24\" *ngIf=\"certificateAuthorityFeatureEnabled | async\">\n            <div>\n              <p class=\"m-b-8 text-medium\">\n                <strong translate>Full registration with device certificate creation</strong>\n              </p>\n              <small class=\"text-muted\" translate>\n                Creates device certificates and devices using the provided list of property values. Once the certificates are provisioned, the devices can immediately start communicating with the platform\n              </small>\n            </div>\n            <div class=\"m-b-16 m-t-16\">\n              <a\n                title=\"{{ 'Download template' | translate }}\"\n                class=\"btn btn-default btn-sm\"\n                target=\"_self\"\n                (click)=\"downloadEst()\"\n              >\n                <i c8yIcon=\"download\"></i>\n                {{ 'Download template' | translate }}\n              </a>\n            </div>\n          </div>\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        [showButtons]=\"{ cancel: true, next: true }\"\n        [disabled]=\"form.invalid\"\n        [pending]=\"pending\"\n        (onCancel)=\"cancel()\"\n        (onNext)=\"upload()\"\n        [labels]=\"{ next: 'Upload' }\"\n      ></c8y-stepper-buttons>\n    </cdk-step>\n\n    <cdk-step state=\"final\">\n      <div class=\"m-24\">\n        <div *ngIf=\"success; else warning\">\n          <c8y-operation-result\n            text=\"{{ message | translate }}\"\n            [size]=\"84\"\n            [vertical]=\"true\"\n            type=\"success\"\n            class=\"lead\"\n          ></c8y-operation-result>\n        </div>\n        <ng-template #warning>\n          <c8y-operation-result\n            text=\"{{ message | translate }}\"\n            [size]=\"84\"\n            [vertical]=\"true\"\n            type=\"error\"\n            class=\"lead\"\n          ></c8y-operation-result>\n        </ng-template>\n        <c8y-list-group class=\"separator-top m-t-16\">\n          <ng-container *ngIf=\"result; else failedResponse\">\n            <c8y-li *ngIf=\"success; else fail\">\n              <c8y-li-icon class=\"text-success\" icon=\"check-circle\"></c8y-li-icon>\n              <p>{{ 'All devices have been processed.' | translate }}</p>\n              <c8y-li-collapse>\n                <pre><code>{{ result | json }}</code></pre>\n              </c8y-li-collapse>\n            </c8y-li>\n            <ng-template #fail>\n              <c8y-li>\n                <c8y-li-icon class=\"text-danger\" icon=\"ban\"></c8y-li-icon>\n                <p\n                  ngNonBindable\n                  [translateParams]=\"{ count: result?.numberOfFailed, total: result?.numberOfAll }\"\n                  translate\n                >\n                  Failed to process {{ count }} out of {{ total }}.\n                </p>\n                <c8y-li-collapse>\n                  <pre><code>{{ result | json }}</code></pre>\n                </c8y-li-collapse>\n              </c8y-li>\n            </ng-template>\n          </ng-container>\n          <ng-template #failedResponse>\n            <c8y-li>\n              <c8y-li-icon class=\"text-danger\" [icon]=\"'ban'\"></c8y-li-icon>\n              <small>{{ failedResult?.message | translate }}</small>\n              <c8y-li-collapse>\n                <pre><code>{{ failedResult | json }}</code></pre>\n              </c8y-li-collapse>\n            </c8y-li>\n          </ng-template>\n        </c8y-list-group>\n      </div>\n      <c8y-stepper-buttons\n        class=\"sticky-bottom d-block p-t-16 p-b-16 separator-top bg-level-0\"\n        [showButtons]=\"{ next: true }\"\n        (onNext)=\"complete()\"\n        [labels]=\"{ next: success ? 'Close' : 'Cancel' }\"\n      ></c8y-stepper-buttons>\n    </cdk-step>\n  </c8y-stepper>\n</c8y-modal>\n", dependencies: [{ kind: "directive", type: i1.IconDirective, selector: "[c8yIcon]", inputs: ["c8yIcon"] }, { kind: "directive", type: i1.C8yTranslateDirective, selector: "[translate],[ngx-translate]" }, { kind: "directive", type: i6.NgIf, selector: "[ngIf]", inputs: ["ngIf", "ngIfThen", "ngIfElse"] }, { kind: "component", type: i1.OperationResultComponent, selector: "c8y-operation-result", inputs: ["text", "vertical", "size", "type"] }, { kind: "component", type: i1.ModalComponent, selector: "c8y-modal", inputs: ["disabled", "close", "dismiss", "title", "body", "customFooter", "headerClasses", "labels"], outputs: ["onDismiss", "onClose"] }, { kind: "component", type: i1.FormGroupComponent, selector: "c8y-form-group", inputs: ["hasError", "hasWarning", "hasSuccess", "novalidation", "status"] }, { kind: "component", type: i1.C8yStepper, selector: "c8y-stepper", inputs: ["disableDefaultIcons", "disableProgressButtons", "customClasses", "hideStepProgress", "useStepLabelsAsTitlesOnly"], outputs: ["onStepChange"] }, { kind: "component", type: i7.CdkStep, selector: "cdk-step", inputs: ["stepControl", "label", "errorMessage", "aria-label", "aria-labelledby", "state", "editable", "optional", "completed", "hasError"], outputs: ["interacted"], exportAs: ["cdkStep"] }, { kind: "component", type: i1.C8yStepperButtons, selector: "c8y-stepper-buttons", inputs: ["labels", "pending", "disabled", "showButtons"], outputs: ["onCancel", "onNext", "onBack", "onCustom"] }, { kind: "component", type: i1.ListGroupComponent, selector: "c8y-list-group" }, { kind: "component", type: i1.ListItemComponent, selector: "c8y-list-item, c8y-li", inputs: ["active", "highlighted", "emptyActions", "dense", "collapsed", "selectable"], outputs: ["collapsedChange"] }, { kind: "component", type: i1.ListItemIconComponent, selector: "c8y-list-item-icon, c8y-li-icon", inputs: ["icon", "status"] }, { kind: "component", type: i1.ListItemCollapseComponent, selector: "c8y-list-item-collapse, c8y-li-collapse", inputs: ["collapseWay"] }, { kind: "component", type: i8.FormlyForm, selector: "formly-form", inputs: ["form", "model", "fields", "options"], outputs: ["modelChange"] }, { kind: "pipe", type: i1.C8yTranslatePipe, name: "translate" }, { kind: "pipe", type: i6.AsyncPipe, name: "async" }, { kind: "pipe", type: i6.JsonPipe, name: "json" }] }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "18.2.13", ngImport: i0, type: BulkDeviceRegistrationModalComponent, decorators: [{
            type: Component,
            args: [{ selector: 'bulk-device-registration', template: "<c8y-modal\n  [title]=\"'Bulk device registration' | translate\"\n  [headerClasses]=\"'dialog-header'\"\n  [customFooter]=\"true\"\n>\n  <ng-container c8y-modal-title>\n    <i c8yIcon=\"upload\"></i>\n  </ng-container>\n\n  <c8y-stepper [hideStepProgress]=\"true\" linear id=\"modal-body\">\n    <cdk-step>\n      <p class=\"modal-subtitle sticky-top\" translate>Register devices in bulk</p>\n\n      <c8y-form-group class=\"d-block p-24 p-t-16 p-b-0 m-b-0\">\n        <formly-form [form]=\"form\" [fields]=\"template\" [model]=\"model\"></formly-form>\n      </c8y-form-group>\n\n      <div class=\"p-24 m-t-0 bg-level-1\">\n          <div class=\"bg-gray-white separator-bottom p-t-16 p-b-16 p-l-24 p-r-24\">\n            <div>\n              <p class=\"m-b-8 text-medium\">\n                <strong translate>Simple registration</strong>\n              </p>\n              <small class=\"text-muted\" translate>\n                Creates all registration requests at once, then each one needs to go through regular\n                acceptance process.\n              </small>\n            </div>\n            <div class=\"m-b-16 m-t-16\">\n              <a\n                title=\"{{ 'Download template' | translate }}\"\n                class=\"btn btn-default btn-sm\"\n                target=\"_self\"\n                (click)=\"downloadSimple()\"\n              >\n                <i c8yIcon=\"download\" translate></i>\n                {{ 'Download template' | translate }}\n              </a>\n            </div>\n          </div>\n          <div class=\"bg-gray-white separator-bottom p-t-16 p-b-16 p-l-24 p-r-24\">\n            <div>\n              <p class=\"m-b-8 text-medium\">\n                <strong translate>Full registration</strong>\n              </p>\n              <small class=\"text-muted\" translate>\n                Creates all device credentials and devices using provided list of property values.\n                Devices can start communicating with the platform immediately.\n              </small>\n            </div>\n            <div class=\"m-b-16 m-t-16\">\n              <a\n                title=\"{{ 'Download template' | translate }}\"\n                class=\"btn btn-default btn-sm\"\n                target=\"_self\"\n                (click)=\"downloadFull()\"\n              >\n                <i c8yIcon=\"download\" translate></i>\n                {{ 'Download template' | translate }}\n              </a>\n            </div>\n          </div>\n          <div class=\"bg-gray-white separator-bottom p-t-16 p-b-16 p-l-24 p-r-24\" *ngIf=\"certificateAuthorityFeatureEnabled | async\">\n            <div>\n              <p class=\"m-b-8 text-medium\">\n                <strong translate>Full registration with device certificate creation</strong>\n              </p>\n              <small class=\"text-muted\" translate>\n                Creates device certificates and devices using the provided list of property values. Once the certificates are provisioned, the devices can immediately start communicating with the platform\n              </small>\n            </div>\n            <div class=\"m-b-16 m-t-16\">\n              <a\n                title=\"{{ 'Download template' | translate }}\"\n                class=\"btn btn-default btn-sm\"\n                target=\"_self\"\n                (click)=\"downloadEst()\"\n              >\n                <i c8yIcon=\"download\"></i>\n                {{ 'Download template' | translate }}\n              </a>\n            </div>\n          </div>\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        [showButtons]=\"{ cancel: true, next: true }\"\n        [disabled]=\"form.invalid\"\n        [pending]=\"pending\"\n        (onCancel)=\"cancel()\"\n        (onNext)=\"upload()\"\n        [labels]=\"{ next: 'Upload' }\"\n      ></c8y-stepper-buttons>\n    </cdk-step>\n\n    <cdk-step state=\"final\">\n      <div class=\"m-24\">\n        <div *ngIf=\"success; else warning\">\n          <c8y-operation-result\n            text=\"{{ message | translate }}\"\n            [size]=\"84\"\n            [vertical]=\"true\"\n            type=\"success\"\n            class=\"lead\"\n          ></c8y-operation-result>\n        </div>\n        <ng-template #warning>\n          <c8y-operation-result\n            text=\"{{ message | translate }}\"\n            [size]=\"84\"\n            [vertical]=\"true\"\n            type=\"error\"\n            class=\"lead\"\n          ></c8y-operation-result>\n        </ng-template>\n        <c8y-list-group class=\"separator-top m-t-16\">\n          <ng-container *ngIf=\"result; else failedResponse\">\n            <c8y-li *ngIf=\"success; else fail\">\n              <c8y-li-icon class=\"text-success\" icon=\"check-circle\"></c8y-li-icon>\n              <p>{{ 'All devices have been processed.' | translate }}</p>\n              <c8y-li-collapse>\n                <pre><code>{{ result | json }}</code></pre>\n              </c8y-li-collapse>\n            </c8y-li>\n            <ng-template #fail>\n              <c8y-li>\n                <c8y-li-icon class=\"text-danger\" icon=\"ban\"></c8y-li-icon>\n                <p\n                  ngNonBindable\n                  [translateParams]=\"{ count: result?.numberOfFailed, total: result?.numberOfAll }\"\n                  translate\n                >\n                  Failed to process {{ count }} out of {{ total }}.\n                </p>\n                <c8y-li-collapse>\n                  <pre><code>{{ result | json }}</code></pre>\n                </c8y-li-collapse>\n              </c8y-li>\n            </ng-template>\n          </ng-container>\n          <ng-template #failedResponse>\n            <c8y-li>\n              <c8y-li-icon class=\"text-danger\" [icon]=\"'ban'\"></c8y-li-icon>\n              <small>{{ failedResult?.message | translate }}</small>\n              <c8y-li-collapse>\n                <pre><code>{{ failedResult | json }}</code></pre>\n              </c8y-li-collapse>\n            </c8y-li>\n          </ng-template>\n        </c8y-list-group>\n      </div>\n      <c8y-stepper-buttons\n        class=\"sticky-bottom d-block p-t-16 p-b-16 separator-top bg-level-0\"\n        [showButtons]=\"{ next: true }\"\n        (onNext)=\"complete()\"\n        [labels]=\"{ next: success ? 'Close' : 'Cancel' }\"\n      ></c8y-stepper-buttons>\n    </cdk-step>\n  </c8y-stepper>\n</c8y-modal>\n" }]
        }], ctorParameters: () => [{ type: i1.C8yJSONSchema }, { type: i2.DeviceRegistrationBulkService }, { type: i3.RegisterDeviceService }, { type: i4.BsModalRef }, { type: i1.GainsightService }, { type: i1.FeatureCacheService }, { type: i5.TranslateService }], propDecorators: { stepper: [{
                type: ViewChild,
                args: [C8yStepper, { static: true }]
            }] } });
//# sourceMappingURL=data:application/json;base64, 