import { Component } from '@angular/core';
import { isEmpty, pull } from 'lodash-es';
import { CrlService } from '@c8y/client';
import { AlertService, gettext, ModalService, Status } from '@c8y/ngx-components';
import { saveAs } from 'file-saver';
import * as i0 from "@angular/core";
import * as i1 from "@c8y/client";
import * as i2 from "@c8y/ngx-components";
import * as i3 from "@angular/common";
import * as i4 from "@angular/forms";
import * as i5 from "ngx-bootstrap/datepicker";
import * as i6 from "ngx-bootstrap/popover";
import * as i7 from "./crl-check-settings.component";
export class CrlSettingsComponent {
    constructor(crlService, alertService, modalService) {
        this.crlService = crlService;
        this.alertService = alertService;
        this.modalService = modalService;
        this.crls = [this.getEmptyCertificateRevocation()];
        this.droppedFiles = [];
        this.today = new Date();
        this.MANUAL_ENTRY_POPOVER = gettext('In this section, you can override or add individual entries to the CRL. Providing the serial number is mandatory. In case the revocation date is not set, it will be configured to the current date.');
        this.FILE_UPLOAD_POPOVER = gettext('In this section, you can upload a file with the list of certificates to be revoked. The file must be in CSV format, and it should include the serial number and revocation date. If the revocation date is empty, it will be set to the current date.');
    }
    async downloadCrl() {
        let arrayBuffer;
        try {
            const res = await this.crlService.downloadCrlFile();
            arrayBuffer = await res.arrayBuffer();
            const fileBinary = new File([arrayBuffer], 'cumulocity.crl', {
                type: 'application/pkix-crl'
            });
            saveAs(fileBinary);
        }
        catch (ex) {
            this.alertService.addServerFailure(ex);
        }
    }
    downloadCrlTemplate() {
        const blob = new Blob([`SERIALNO,DATE\nSERIAL_NO1,${new Date().toISOString()}`], {
            type: 'text/csv;charset=utf-8;'
        });
        const fileName = 'crl-template';
        saveAs(blob, `${fileName}.csv`);
    }
    addCertificateRevocation() {
        this.crls.push(this.getEmptyCertificateRevocation());
    }
    removeCertificateRevocation(certificateRevocation) {
        pull(this.crls, certificateRevocation);
        if (this.crls.length === 0) {
            this.addCertificateRevocation();
        }
    }
    async save() {
        try {
            await this.confirm();
            await this.saveCrls();
            await this.uploadCrlFile();
            await this.clearSavedData();
            this.alertService.success(gettext('CRL saved.'));
        }
        catch (er) {
            this.alertService.addServerFailure(er);
        }
    }
    get isListEmpty() {
        return this.crls.length === 1 && isEmpty(this.crls[0].serialNumberInHex);
    }
    get isFileDropped() {
        return !!(this.droppedFiles && this.droppedFiles[0]);
    }
    async confirm() {
        const isOverrideManualEntries = !this.isListEmpty && this.isFileDropped;
        const status = isOverrideManualEntries ? Status.DANGER : Status.WARNING;
        const body = isOverrideManualEntries
            ? gettext('You are about to update the CRL. The CRL file content will override manual entries. Do you want to proceed?')
            : gettext('You are about to update the CRL. Do you want to proceed?');
        await this.modalService.confirm(gettext('Update the CRL'), body, status, {
            ok: gettext('Update')
        });
    }
    clearSavedData() {
        this.droppedFiles = [];
        this.crls = [this.getEmptyCertificateRevocation()];
    }
    async saveCrls() {
        if (!this.isListEmpty) {
            await this.crlService.uploadCrls(this.crls);
        }
    }
    async uploadCrlFile() {
        if (this.isFileDropped) {
            await this.crlService.uploadCrlFile(this.droppedFiles[0].file);
        }
    }
    getEmptyCertificateRevocation() {
        return {
            serialNumberInHex: ''
        };
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "18.2.9", ngImport: i0, type: CrlSettingsComponent, deps: [{ token: i1.CrlService }, { token: i2.AlertService }, { token: i2.ModalService }], target: i0.ɵɵFactoryTarget.Component }); }
    static { this.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "18.2.9", type: CrlSettingsComponent, selector: "c8y-crl-settings", ngImport: i0, template: "<c8y-title>{{ 'Trusted certificates' | translate }}</c8y-title>\n\n<c8y-breadcrumb>\n  <c8y-breadcrumb-item\n    icon=\"c8y-management\"\n    label=\"{{ 'Management' | translate }}\"\n  ></c8y-breadcrumb-item>\n  <c8y-breadcrumb-item\n    icon=\"certificate\"\n    label=\"{{ 'Trusted certificates' | translate }}\"\n  ></c8y-breadcrumb-item>\n</c8y-breadcrumb>\n\n<c8y-crl-check-settings></c8y-crl-check-settings>\n\n<c8y-help\n  [icon]=\"'settings'\"\n  src=\"/docs/device-certificate-authentication/managing-trusted-certificate-settings/#managing-trusted-certificate-settings\"\n></c8y-help>\n\n<form\n  class=\"card card--fullpage\"\n  #crlManualForm=\"ngForm\"\n  novalidate\n>\n  <div class=\"card-header separator\">\n    <div class=\"card-title\">\n      {{ 'Offline configuration of Certificate Revocation List (CRL)' | translate }}\n    </div>\n  </div>\n  <div class=\"inner-scroll\">\n    <div class=\"card-block\">\n      <div class=\"legend form-block\">\n        {{ 'Manual' | translate }}\n        <button\n          class=\"btn-help btn-help--sm\"\n          [attr.aria-label]=\"'Help' | translate\"\n          popover=\"{{ MANUAL_ENTRY_POPOVER | translate }}\"\n          placement=\"right\"\n          triggers=\"focus\"\n          container=\"body\"\n          type=\"button\"\n        ></button>\n      </div>\n\n      <div\n        class=\"row tight-grid\"\n        data-cy=\"c8y-row-grid--new-row\"\n        *ngFor=\"let certificateRevocation of crls; index as index; last as isLast\"\n      >\n        <div class=\"col-sm-5\">\n          <c8y-form-group>\n            <label\n              [for]=\"'serialNumber' + index\"\n              translate\n            >\n              Serial number\n            </label>\n            <input\n              class=\"form-control\"\n              required\n              [name]=\"'serialNumber' + index\"\n              [id]=\"'serialNumber' + index\"\n              [(ngModel)]=\"certificateRevocation.serialNumberInHex\"\n              [placeholder]=\"'e.g. {{ example }}' | translate: { example: '8ab34fe5476' }\"\n              c8yDefaultValidation=\"colonedHexNumber\"\n            />\n          </c8y-form-group>\n        </div>\n        <div class=\"col-sm-5\">\n          <c8y-form-group class=\"datepicker\">\n            <label [for]=\"'validTillPicker' + index\">\n              {{ 'Valid till' | translate }}\n            </label>\n            <input\n              class=\"form-control\"\n              [attr.aria-label]=\"'Date to' | translate\"\n              placeholder=\"{{ 'Date to' | translate }}\"\n              [name]=\"'validTillPicker' + index\"\n              [id]=\"'validTillPicker' + index\"\n              [(ngModel)]=\"certificateRevocation.revocationDate\"\n              [bsConfig]=\"{ customTodayClass: 'today' }\"\n              bsDatepicker\n              [maxDate]=\"today\"\n            />\n          </c8y-form-group>\n        </div>\n        <div class=\"col-sm-2\">\n          <c8y-form-group>\n            <div class=\"p-t-24\">\n              <button\n                class=\"btn btn-link hidden-xs hidden-sm\"\n                title=\"{{ 'Remove' | translate }}\"\n                type=\"button\"\n                *ngIf=\"crls.length > 1\"\n                (click)=\"removeCertificateRevocation(certificateRevocation)\"\n              >\n                <i\n                  class=\"text-danger\"\n                  c8yIcon=\"minus-circle\"\n                ></i>\n              </button>\n              <button\n                class=\"btn btn-link hidden-xs hidden-sm\"\n                title=\"{{ 'Add' | translate }}\"\n                type=\"button\"\n                (click)=\"addCertificateRevocation()\"\n                *ngIf=\"isLast\"\n              >\n                <i\n                  class=\"text-primary\"\n                  c8yIcon=\"plus-circle\"\n                ></i>\n              </button>\n\n              <button\n                class=\"btn btn-danger btn-block btn-sm visible-xs visible-sm\"\n                title=\"{{ 'Remove' | translate }}\"\n                type=\"button\"\n                *ngIf=\"crls.length > 1\"\n                (click)=\"removeCertificateRevocation(certificateRevocation)\"\n              >\n                <i c8yIcon=\"minus-circle\"></i>\n                {{ 'Remove' | translate }}\n              </button>\n              <button\n                class=\"btn btn-primary btn-block btn-sm visible-xs visible-sm\"\n                title=\"{{ 'Add' | translate }}\"\n                type=\"button\"\n                (click)=\"addCertificateRevocation()\"\n                *ngIf=\"isLast\"\n              >\n                <i c8yIcon=\"plus-circle\"></i>\n                {{ 'Add' | translate }}\n              </button>\n            </div>\n          </c8y-form-group>\n        </div>\n      </div>\n      <div class=\"legend form-block center\">\n        {{ 'or' | translate }}\n      </div>\n      <div class=\"legend form-block\">\n        {{ 'File upload' | translate }}\n        <button\n          class=\"btn-help btn-help--sm\"\n          [attr.aria-label]=\"'Help' | translate\"\n          popover=\"{{ FILE_UPLOAD_POPOVER | translate }}\"\n          placement=\"right\"\n          triggers=\"focus\"\n          container=\"body\"\n          type=\"button\"\n        ></button>\n      </div>\n\n      <c8y-drop-area\n        class=\"drop-area-sm\"\n        [title]=\"'Upload CRL file (.csv format)' | translate\"\n        name=\"uploadCrlDropArea\"\n        [(ngModel)]=\"droppedFiles\"\n        [message]=\"'Upload CRL file (.csv format)' | translate\"\n        [loadingMessage]=\"'Uploading\u2026' | translate\"\n        [accept]=\"'.csv'\"\n        [maxAllowedFiles]=\"1\"\n      ></c8y-drop-area>\n      <p class=\"help-block has-info text-muted m-t-4\">\n        {{ 'CRL file content will override manual entries.' | translate }}\n      </p>\n\n      <button\n        class=\"btn btn-sm btn-default m-t-16\"\n        title=\"{{ 'Download template' | translate }}\"\n        type=\"button\"\n        (click)=\"downloadCrlTemplate()\"\n      >\n        <i\n          class=\"m-r-4\"\n          c8yIcon=\"template\"\n        ></i>\n        {{ 'Download template' | translate }}\n      </button>\n    </div>\n  </div>\n  <div class=\"card-footer separator\">\n    <button\n      class=\"btn btn-default\"\n      title=\"{{ 'Download CRL file' | translate }}\"\n      type=\"button\"\n      (click)=\"downloadCrl()\"\n    >\n      <i\n        class=\"m-r-4\"\n        c8yIcon=\"download\"\n      ></i>\n      {{ 'Download CRL file' | translate }}\n    </button>\n    <button\n      class=\"btn btn-primary\"\n      title=\"{{ 'Save' | translate }}\"\n      type=\"submit\"\n      (click)=\"save()\"\n      [disabled]=\"!(crlManualForm.form.valid || isListEmpty) || (isListEmpty && !isFileDropped)\"\n    >\n      {{ 'Save' | translate }}\n    </button>\n  </div>\n</form>\n", dependencies: [{ kind: "component", type: i2.BreadcrumbComponent, selector: "c8y-breadcrumb" }, { kind: "component", type: i2.BreadcrumbItemComponent, selector: "c8y-breadcrumb-item", inputs: ["icon", "translate", "label", "path", "injector"] }, { kind: "directive", type: i2.IconDirective, selector: "[c8yIcon]", inputs: ["c8yIcon"] }, { kind: "directive", type: i2.C8yTranslateDirective, selector: "[translate],[ngx-translate]" }, { kind: "directive", type: i3.NgForOf, selector: "[ngFor][ngForOf]", inputs: ["ngForOf", "ngForTrackBy", "ngForTemplate"] }, { kind: "directive", type: i3.NgIf, selector: "[ngIf]", inputs: ["ngIf", "ngIfThen", "ngIfElse"] }, { kind: "component", type: i2.DropAreaComponent, selector: "c8y-drop-area", inputs: ["formControl", "title", "message", "icon", "loadingMessage", "forceHideList", "alwaysShow", "clickToOpen", "loading", "progress", "maxAllowedFiles", "files", "maxFileSizeInMegaBytes", "accept"], outputs: ["dropped"] }, { kind: "component", type: i2.TitleComponent, selector: "c8y-title", inputs: ["pageTitleUpdate"] }, { kind: "directive", type: i2.DefaultValidationDirective, selector: "[c8yDefaultValidation]", inputs: ["c8yDefaultValidation"] }, { kind: "directive", type: i4.ɵNgNoValidate, selector: "form:not([ngNoForm]):not([ngNativeValidate])" }, { kind: "directive", type: i4.DefaultValueAccessor, selector: "input:not([type=checkbox])[formControlName],textarea[formControlName],input:not([type=checkbox])[formControl],textarea[formControl],input:not([type=checkbox])[ngModel],textarea[ngModel],[ngDefaultControl]" }, { kind: "directive", type: i4.NgControlStatus, selector: "[formControlName],[ngModel],[formControl]" }, { kind: "directive", type: i4.NgControlStatusGroup, selector: "[formGroupName],[formArrayName],[ngModelGroup],[formGroup],form:not([ngNoForm]),[ngForm]" }, { kind: "directive", type: i4.RequiredValidator, selector: ":not([type=checkbox])[required][formControlName],:not([type=checkbox])[required][formControl],:not([type=checkbox])[required][ngModel]", inputs: ["required"] }, { kind: "directive", type: i4.NgModel, selector: "[ngModel]:not([formControlName]):not([formControl])", inputs: ["name", "disabled", "ngModel", "ngModelOptions"], outputs: ["ngModelChange"], exportAs: ["ngModel"] }, { kind: "directive", type: i4.NgForm, selector: "form:not([ngNoForm]):not([formGroup]),ng-form,[ngForm]", inputs: ["ngFormOptions"], outputs: ["ngSubmit"], exportAs: ["ngForm"] }, { kind: "component", type: i2.FormGroupComponent, selector: "c8y-form-group", inputs: ["hasError", "hasWarning", "hasSuccess", "novalidation", "status"] }, { kind: "directive", type: i2.RequiredInputPlaceholderDirective, selector: "input[required], input[formControlName]" }, { kind: "component", type: i2.HelpComponent, selector: "c8y-help", inputs: ["src", "isCollapsed", "priority", "icon"] }, { kind: "directive", type: i5.BsDatepickerDirective, selector: "[bsDatepicker]", inputs: ["placement", "triggers", "outsideClick", "container", "outsideEsc", "isDisabled", "minDate", "maxDate", "minMode", "daysDisabled", "datesDisabled", "datesEnabled", "dateCustomClasses", "dateTooltipTexts", "isOpen", "bsValue", "bsConfig"], outputs: ["onShown", "onHidden", "bsValueChange"], exportAs: ["bsDatepicker"] }, { kind: "directive", type: i5.BsDatepickerInputDirective, selector: "input[bsDatepicker]" }, { kind: "directive", type: i6.PopoverDirective, selector: "[popover]", inputs: ["adaptivePosition", "boundariesElement", "popover", "popoverContext", "popoverTitle", "placement", "outsideClick", "triggers", "container", "containerClass", "isOpen", "delay"], outputs: ["onShown", "onHidden"], exportAs: ["bs-popover"] }, { kind: "component", type: i7.CrlCheckSettingsComponent, selector: "c8y-crl-check-settings" }, { kind: "pipe", type: i2.C8yTranslatePipe, name: "translate" }] }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "18.2.9", ngImport: i0, type: CrlSettingsComponent, decorators: [{
            type: Component,
            args: [{ selector: 'c8y-crl-settings', template: "<c8y-title>{{ 'Trusted certificates' | translate }}</c8y-title>\n\n<c8y-breadcrumb>\n  <c8y-breadcrumb-item\n    icon=\"c8y-management\"\n    label=\"{{ 'Management' | translate }}\"\n  ></c8y-breadcrumb-item>\n  <c8y-breadcrumb-item\n    icon=\"certificate\"\n    label=\"{{ 'Trusted certificates' | translate }}\"\n  ></c8y-breadcrumb-item>\n</c8y-breadcrumb>\n\n<c8y-crl-check-settings></c8y-crl-check-settings>\n\n<c8y-help\n  [icon]=\"'settings'\"\n  src=\"/docs/device-certificate-authentication/managing-trusted-certificate-settings/#managing-trusted-certificate-settings\"\n></c8y-help>\n\n<form\n  class=\"card card--fullpage\"\n  #crlManualForm=\"ngForm\"\n  novalidate\n>\n  <div class=\"card-header separator\">\n    <div class=\"card-title\">\n      {{ 'Offline configuration of Certificate Revocation List (CRL)' | translate }}\n    </div>\n  </div>\n  <div class=\"inner-scroll\">\n    <div class=\"card-block\">\n      <div class=\"legend form-block\">\n        {{ 'Manual' | translate }}\n        <button\n          class=\"btn-help btn-help--sm\"\n          [attr.aria-label]=\"'Help' | translate\"\n          popover=\"{{ MANUAL_ENTRY_POPOVER | translate }}\"\n          placement=\"right\"\n          triggers=\"focus\"\n          container=\"body\"\n          type=\"button\"\n        ></button>\n      </div>\n\n      <div\n        class=\"row tight-grid\"\n        data-cy=\"c8y-row-grid--new-row\"\n        *ngFor=\"let certificateRevocation of crls; index as index; last as isLast\"\n      >\n        <div class=\"col-sm-5\">\n          <c8y-form-group>\n            <label\n              [for]=\"'serialNumber' + index\"\n              translate\n            >\n              Serial number\n            </label>\n            <input\n              class=\"form-control\"\n              required\n              [name]=\"'serialNumber' + index\"\n              [id]=\"'serialNumber' + index\"\n              [(ngModel)]=\"certificateRevocation.serialNumberInHex\"\n              [placeholder]=\"'e.g. {{ example }}' | translate: { example: '8ab34fe5476' }\"\n              c8yDefaultValidation=\"colonedHexNumber\"\n            />\n          </c8y-form-group>\n        </div>\n        <div class=\"col-sm-5\">\n          <c8y-form-group class=\"datepicker\">\n            <label [for]=\"'validTillPicker' + index\">\n              {{ 'Valid till' | translate }}\n            </label>\n            <input\n              class=\"form-control\"\n              [attr.aria-label]=\"'Date to' | translate\"\n              placeholder=\"{{ 'Date to' | translate }}\"\n              [name]=\"'validTillPicker' + index\"\n              [id]=\"'validTillPicker' + index\"\n              [(ngModel)]=\"certificateRevocation.revocationDate\"\n              [bsConfig]=\"{ customTodayClass: 'today' }\"\n              bsDatepicker\n              [maxDate]=\"today\"\n            />\n          </c8y-form-group>\n        </div>\n        <div class=\"col-sm-2\">\n          <c8y-form-group>\n            <div class=\"p-t-24\">\n              <button\n                class=\"btn btn-link hidden-xs hidden-sm\"\n                title=\"{{ 'Remove' | translate }}\"\n                type=\"button\"\n                *ngIf=\"crls.length > 1\"\n                (click)=\"removeCertificateRevocation(certificateRevocation)\"\n              >\n                <i\n                  class=\"text-danger\"\n                  c8yIcon=\"minus-circle\"\n                ></i>\n              </button>\n              <button\n                class=\"btn btn-link hidden-xs hidden-sm\"\n                title=\"{{ 'Add' | translate }}\"\n                type=\"button\"\n                (click)=\"addCertificateRevocation()\"\n                *ngIf=\"isLast\"\n              >\n                <i\n                  class=\"text-primary\"\n                  c8yIcon=\"plus-circle\"\n                ></i>\n              </button>\n\n              <button\n                class=\"btn btn-danger btn-block btn-sm visible-xs visible-sm\"\n                title=\"{{ 'Remove' | translate }}\"\n                type=\"button\"\n                *ngIf=\"crls.length > 1\"\n                (click)=\"removeCertificateRevocation(certificateRevocation)\"\n              >\n                <i c8yIcon=\"minus-circle\"></i>\n                {{ 'Remove' | translate }}\n              </button>\n              <button\n                class=\"btn btn-primary btn-block btn-sm visible-xs visible-sm\"\n                title=\"{{ 'Add' | translate }}\"\n                type=\"button\"\n                (click)=\"addCertificateRevocation()\"\n                *ngIf=\"isLast\"\n              >\n                <i c8yIcon=\"plus-circle\"></i>\n                {{ 'Add' | translate }}\n              </button>\n            </div>\n          </c8y-form-group>\n        </div>\n      </div>\n      <div class=\"legend form-block center\">\n        {{ 'or' | translate }}\n      </div>\n      <div class=\"legend form-block\">\n        {{ 'File upload' | translate }}\n        <button\n          class=\"btn-help btn-help--sm\"\n          [attr.aria-label]=\"'Help' | translate\"\n          popover=\"{{ FILE_UPLOAD_POPOVER | translate }}\"\n          placement=\"right\"\n          triggers=\"focus\"\n          container=\"body\"\n          type=\"button\"\n        ></button>\n      </div>\n\n      <c8y-drop-area\n        class=\"drop-area-sm\"\n        [title]=\"'Upload CRL file (.csv format)' | translate\"\n        name=\"uploadCrlDropArea\"\n        [(ngModel)]=\"droppedFiles\"\n        [message]=\"'Upload CRL file (.csv format)' | translate\"\n        [loadingMessage]=\"'Uploading\u2026' | translate\"\n        [accept]=\"'.csv'\"\n        [maxAllowedFiles]=\"1\"\n      ></c8y-drop-area>\n      <p class=\"help-block has-info text-muted m-t-4\">\n        {{ 'CRL file content will override manual entries.' | translate }}\n      </p>\n\n      <button\n        class=\"btn btn-sm btn-default m-t-16\"\n        title=\"{{ 'Download template' | translate }}\"\n        type=\"button\"\n        (click)=\"downloadCrlTemplate()\"\n      >\n        <i\n          class=\"m-r-4\"\n          c8yIcon=\"template\"\n        ></i>\n        {{ 'Download template' | translate }}\n      </button>\n    </div>\n  </div>\n  <div class=\"card-footer separator\">\n    <button\n      class=\"btn btn-default\"\n      title=\"{{ 'Download CRL file' | translate }}\"\n      type=\"button\"\n      (click)=\"downloadCrl()\"\n    >\n      <i\n        class=\"m-r-4\"\n        c8yIcon=\"download\"\n      ></i>\n      {{ 'Download CRL file' | translate }}\n    </button>\n    <button\n      class=\"btn btn-primary\"\n      title=\"{{ 'Save' | translate }}\"\n      type=\"submit\"\n      (click)=\"save()\"\n      [disabled]=\"!(crlManualForm.form.valid || isListEmpty) || (isListEmpty && !isFileDropped)\"\n    >\n      {{ 'Save' | translate }}\n    </button>\n  </div>\n</form>\n" }]
        }], ctorParameters: () => [{ type: i1.CrlService }, { type: i2.AlertService }, { type: i2.ModalService }] });
//# sourceMappingURL=data:application/json;base64, 