import { __awaiter } from "tslib";
import { Component } from '@angular/core';
import { AlertService, gettext, ModalService, Status } from '@c8y/ngx-components';
import { AddTrustedCertificateComponent } from './add-trusted-certificate.component';
import { BsModalService } from 'ngx-bootstrap/modal';
import { TrustedCertificateService } from '@c8y/client';
import { TranslateService } from '@ngx-translate/core';
import { tap, switchMap } from 'rxjs/operators';
import { pipe, BehaviorSubject } from 'rxjs';
export class TrustedCertificatesComponent {
    constructor(bsModal, alertService, trustedCertificateService, modalService, translateService) {
        this.bsModal = bsModal;
        this.alertService = alertService;
        this.trustedCertificateService = trustedCertificateService;
        this.modalService = modalService;
        this.translateService = translateService;
        this.reloading = new BehaviorSubject(false);
        this.reload = new BehaviorSubject(null);
        this.trustedCertificates = this.reload.pipe(tap(() => this.reloading.next(true)), switchMap(() => this.getTrustedCertificates()), tap(() => this.reloading.next(false)));
        this.sortByExpirationDateAsc = pipe(tap((results) => {
            return results.sort((n1, n2) => n1.notAfter.localeCompare(n2.notAfter));
        }));
    }
    ngOnInit() {
        return __awaiter(this, void 0, void 0, function* () {
            yield this.loadTrustedCertificates();
        });
    }
    loadTrustedCertificates() {
        return __awaiter(this, void 0, void 0, function* () {
            this.reload.next();
        });
    }
    getTrustedCertificates() {
        const filter = {
            pageSize: 1000,
            withTotalPages: true,
        };
        return this.trustedCertificateService.list(filter);
    }
    addTrustedCertificate() {
        return __awaiter(this, void 0, void 0, function* () {
            const modal = this.bsModal.show(AddTrustedCertificateComponent, {
                class: 'modal-sm',
                ignoreBackdropClick: true,
            }).content;
            try {
                yield modal.result;
                modal.close();
                this.reload.next();
            }
            catch (ex) {
                // do nothing
            }
        });
    }
    deleteTrustedCertificate(certificate, index) {
        return __awaiter(this, void 0, void 0, function* () {
            const title = gettext('Delete trusted certificate');
            const confirmationText = gettext('You are about to delete a trusted certificate "{{ certificateName }}".');
            const finalQuestion = gettext('Do you want to proceed?');
            const certificateName = certificate.name;
            const body = [
                this.translateService.instant(confirmationText, {
                    certificateName,
                }),
                this.translateService.instant(finalQuestion),
            ].join(' ');
            try {
                yield this.modalService.confirm(title, body, Status.DANGER, { ok: gettext('Delete') });
                yield this.trustedCertificateService.delete(certificate.fingerprint);
                this.alertService.success(gettext('Certificate deleted.'));
                this.reload.next();
            }
            catch (ex) {
                this.alertService.addServerFailure(ex);
            }
        });
    }
    updateCertificate(trustedCertificate, updatingPart) {
        return __awaiter(this, void 0, void 0, function* () {
            try {
                yield this.trustedCertificateService.update(Object.assign({ fingerprint: trustedCertificate.fingerprint }, updatingPart));
                this.alertService.success(gettext('Certificate saved.'));
            }
            catch (ex) {
                this.alertService.addServerFailure(ex);
            }
        });
    }
    highlightDependingOnExpirationStatus(item) {
        const warningOffset = 24 * 60 * 60 * 1000 * 90; // 90 days
        const todayTimestamp = new Date().getTime();
        const warningTimestamp = new Date().getTime() + warningOffset;
        const notAfterTimestamp = new Date(item.notAfter).getTime();
        const expired = notAfterTimestamp < todayTimestamp;
        const expiresInLessThan90Days = notAfterTimestamp < warningTimestamp;
        if (expired) {
            return 'text-danger';
        }
        if (expiresInLessThan90Days) {
            return 'text-warning';
        }
        return '';
    }
}
TrustedCertificatesComponent.decorators = [
    { type: Component, args: [{
                selector: 'c8y-trusted-certificates',
                template: "<c8y-title>{{ 'Trusted certificates' | translate }}</c8y-title>\n\n<c8y-action-bar-item [placement]=\"'right'\">\n  <button\n    title=\"{{ 'Add trusted certificate' | translate }}\"\n    class=\"btn btn-link\"\n    (click)=\"addTrustedCertificate()\"\n  >\n    <i c8yIcon=\"plus-circle\"></i>\n    {{ 'Add trusted certificate' | translate }}\n  </button>\n</c8y-action-bar-item>\n\n<c8y-action-bar-item [placement]=\"'right'\">\n  <button\n    title=\"{{ 'Reload' | translate }}\"\n    class=\"btn btn-link\"\n    (click)=\"loadTrustedCertificates()\"\n  >\n    <i c8yIcon=\"refresh\" [ngClass]=\"{ 'icon-spin': reloading | async }\"></i>\n    {{ 'Reload' | translate }}\n  </button>\n</c8y-action-bar-item>\n\n<div class=\"c8y-empty-state text-center\" *ngIf=\"(trustedCertificates | async)?.data.length === 0\">\n  <h1 c8yIcon=\"certificate\"></h1>\n  <h3 translate>No trusted certificates to display.</h3>\n  <p translate>Add your first certificate by clicking below.</p>\n  <p>\n    <button\n      title=\"{{ 'Add trusted certificate' | translate }}\"\n      (click)=\"addTrustedCertificate()\"\n      class=\"btn btn-primary\"\n    >\n      {{ 'Add trusted certificate' | translate }}\n    </button>\n  </p>\n</div>\n\n<c8y-list-group \n  [ngClass]=\"{'dd-low': (trustedCertificates | async)?.data.length < 10 }\"\n  class=\"m-b-24\"\n>\n  <div *ngIf=\"(trustedCertificates | async)?.data.length > 0 \"\n    class=\"page-sticky-header hidden-xs c8y-list__item c8y-list__item--double-actions\">\n    <div class=\"c8y-list__item__block\">\n      <div class=\"c8y-list__item__icon\">\n        <i class=\"p-l-24\"></i>\n      </div>\n      <div class=\"c8y-list__item__body\">\n        <div class=\"content-flex-59\">\n          <div class=\"col-3\">\n            <span class=\"text-truncate\" title=\" {{'Certificate' | translate}} \">\n              {{'Certificate' | translate}}\n            </span>\n          </div>\n          <div class=\"col-2\">\n            <span class=\"text-truncate\" title=\"{{'Status' | translate}}\">\n              {{'Status' | translate}}\n            </span>\n          </div>\n          <div class=\"col-2\">\n            <span class=\"text-truncate\" title=\"{{'Algorithm' | translate}}\">\n              {{'Algorithm' | translate}}\n            </span>\n          </div>\n          <div class=\"col-3\">\n            <span class=\"text-truncate\" title=\"{{'Expiration date' | translate}}\">\n              {{'Expiration date' | translate}}\n            </span>\n          </div>\n          <div class=\"col-2\">\n            <span class=\"text-truncate\" title=\" {{'Auto registration' | translate}}\">\n              {{'Auto registration' | translate}}\n            </span>\n          </div>\n        </div>\n      </div>\n      <div class=\"c8y-list__item__actions\"></div>\n    </div>\n  </div>\n  \n  <c8y-li\n    *c8yFor=\"\n      let trustedCertificate of trustedCertificates | async;\n      let i = index;\n      pipe: sortByExpirationDateAsc;\n      loadMore: 'none'\n    \"\n  >\n    <c8y-li-icon>\n      <i c8yIcon=\"certificate\"></i>\n    </c8y-li-icon>\n\n    <c8y-li-body class=\"content-flex-59\">\n      <div class=\"col-3\">\n        <span class=\"text-truncate\" title=\"{{ trustedCertificate.name }}\">\n          {{ trustedCertificate.name }}\n        </span>\n      </div>\n      <div class=\"col-2\">\n        <div class=\"visible-xs p-8\"></div>\n        <button\n          type=\"button\"\n          class=\"btn c8y-btn-checkbox--inline\"\n          name=\"certificateStatus\"\n          [(ngModel)]=\"trustedCertificate.status\"\n          btnCheckbox\n          btnCheckboxTrue=\"ENABLED\"\n          btnCheckboxFalse=\"DISABLED\"\n          (ngModelChange)=\"updateCertificate(trustedCertificate, { status: $event })\"\n        >\n          <small\n            title=\"{{ 'Disabled`trusted certificate status`' | translate }}\"\n            [hidden]=\"trustedCertificate.status !== 'DISABLED'\"\n          >\n            {{ 'Disabled`trusted certificate status`' | translate }}\n          </small>\n          <small\n            title=\"{{ 'Enabled`trusted certificate status`' | translate }}\"\n            [hidden]=\"trustedCertificate.status !== 'ENABLED'\"\n          >\n            {{ 'Enabled`trusted certificate status`' | translate }}\n          </small>\n        </button>\n        <div class=\"visible-xs p-8\"></div>\n      </div>\n      <div class=\"col-2\">\n        <div class=\"text-truncate\" title=\"{{'Algorithm' | translate }}: {{ trustedCertificate.algorithmName }}\">\n          <span class=\"text-label-small m-t-8 m-r-8 visible-xs-inline \" translate>Algorithm</span>\n          {{ trustedCertificate.algorithmName }}\n        </div>\n      </div>\n\n      <div class=\"col-3\">\n        <div class=\"text-truncate\" \n          title=\"{{'Expiration date' | translate}}: {{ trustedCertificate.notAfter | c8yDate }}\">\n          <span class=\"text-label-small m-t-8 m-r-8 visible-xs-inline\" translate>Expiration date</span>\n          <small [ngClass]=\"highlightDependingOnExpirationStatus(trustedCertificate)\">\n            <i c8yIcon=\"calendar\" class=\"m-r-4\" *ngIf=\"!highlightDependingOnExpirationStatus(trustedCertificate)\"></i>\n            <i c8yIcon=\"warning\" class=\"m-r-4\" *ngIf=\"highlightDependingOnExpirationStatus(trustedCertificate)\"></i>\n            <span>{{ trustedCertificate.notAfter | c8yDate }}</span>\n          </small>\n        </div>\n      </div>\n      <div class=\"col-2\">\n        <div class=\"text-truncate\">\n          <span class=\"text-label-small m-t-8 m-r-4 visible-xs-inline\">\n            {{ 'Auto registration' | translate }}</span>\n          <span *ngIf=\"trustedCertificate.autoRegistrationEnabled\"\n          title=\"{{ 'Auto registration' | translate }}:  {{ 'Enabled`auto registration`' | translate }}\">\n            {{ 'Enabled`auto registration`' | translate }}\n          </span>\n          <span *ngIf=\"!trustedCertificate.autoRegistrationEnabled\"\n          title=\"{{ 'Auto registration' | translate }}:  {{ 'Disabled`auto registration`' | translate }}\">\n            {{ 'Disabled`auto registration`' | translate }}\n          </span>\n        </div>\n      </div>\n    </c8y-li-body>\n\n    <c8y-li-action\n      (click)=\"deleteTrustedCertificate(trustedCertificate, i)\"\n      icon=\"trash\"\n      label=\"{{ 'Delete' | translate }}\"\n    >\n    </c8y-li-action>\n\n    <c8y-li-collapse>\n      <div class=\"p-t-16 p-b-16\">\n        <div class=\"row\">\n          <div class=\"col-md-4\">\n            <c8y-form-group>\n              <label class=\"control-label\">\n                {{ 'Certificate name' | translate }}\n              </label>\n              <div class=\"input-group input-group-editable\">\n                <input\n                  type=\"text\"\n                  class=\"form-control\"\n                  [(ngModel)]=\"trustedCertificate.name\"\n                  required\n                />\n                <span></span>\n                <div class=\"input-group-btn\">\n                  <button\n                    title=\"{{ 'Update certificate name' | translate }}\"\n                    (click)=\"\n                      updateCertificate(trustedCertificate, { name: trustedCertificate.name })\n                    \"\n                    class=\"btn btn-primary\"\n                    [disabled]=\"!trustedCertificate.name\"\n                  >\n                    {{ 'Save' | translate }}\n                  </button>\n                </div>\n              </div>\n            </c8y-form-group>\n            <div class=\"legend form-block\" translate>Additional properties</div>\n            <ul class=\"list-unstyled\">\n              <li class=\"p-t-4 p-b-4 flex-row separator-bottom\" >\n                <label class=\"small m-b-0 m-r-8 flex-item-v-start flex-grow\">\n                  {{ 'Algorithm' | translate }}\n                </label>\n                <span class=\"flex-item-right text-break-word\">\n                  {{ trustedCertificate.algorithmName }}\n                </span>\n              </li>\n              <li class=\"p-t-4 p-b-4 flex-row separator-bottom\">\n                <label class=\"small m-b-0 m-r-8 flex-item-v-start flex-grow\">\n                  {{ 'Version' | translate }}\n                </label>\n                <span class=\"flex-item-right text-break-word\">\n                  {{ trustedCertificate.version }}\n                </span>\n              </li>\n              <li class=\"p-t-4 p-b-4 flex-row separator-bottom\">\n                <label class=\"small m-b-0 m-r-8 flex-item-v-start flex-grow\">\n                  {{ 'Valid from' | translate }}\n                </label>\n                <span class=\"flex-item-right text-break-word\">\n                  {{ trustedCertificate.notBefore | c8yDate }}\n                </span>\n              </li>\n              <li class=\"p-t-4 p-b-4 flex-row separator-bottom\">\n                <label class=\"small m-b-0 m-r-8 flex-item-v-start flex-grow\">\n                  {{ 'Issuer' | translate }}\n                </label>\n                <span class=\"flex-item-right text-break-word\">\n                  {{ trustedCertificate.issuer }}\n                </span>\n              </li>\n              <li class=\"p-t-4 p-b-4 flex-row separator-bottom\">\n                <label class=\"small m-b-0 m-r-8 flex-item-v-start flex-grow\">\n                  {{ 'Expiration date' | translate }}\n                </label>\n                <span class=\"flex-item-right text-break-word\">\n                  {{ trustedCertificate.notAfter | c8yDate }}\n                </span>\n              </li>\n              <li class=\"p-t-4 p-b-4 flex-row separator-bottom\">\n                <label class=\"small m-b-0 m-r-8 flex-item-v-start flex-grow\">\n                  {{ 'Serial number' | translate }}\n                </label>\n                <span class=\"flex-item-right text-break-word\">\n                  {{ trustedCertificate.serialNumber }}\n                </span>\n              </li>\n              <li class=\"p-t-4 p-b-4 flex-row separator-bottom\">\n                <label class=\"small m-b-0 m-r-8 flex-item-v-start flex-grow\">\n                  {{ 'Subject`of a certificate`' | translate }}\n                </label>\n                <span class=\"flex-item-right text-break-word\">\n                  {{ trustedCertificate.subject }}\n                </span>\n              </li>\n            </ul>\n          </div>\n          <div class=\"col-md-1\"></div>\n          <div class=\"col-md-7 col-lg-5\">\n            <c8y-form-group>\n              <label class=\"control-label\" translate>\n                Certificate\n              </label>\n              <textarea\n                class=\"form-control no-resize\"\n                name=\"name\"\n                type=\"text\"\n                rows=\"15\"\n                readonly\n                [(ngModel)]=\"trustedCertificate.certInPemFormat\"\n              >\n              </textarea>\n            </c8y-form-group>\n            <c8y-form-group>\n              <label title=\"{{ 'Auto registration' | translate }}\" class=\"c8y-checkbox\">\n                <input\n                  type=\"checkbox\"\n                  [(ngModel)]=\"trustedCertificate.autoRegistrationEnabled\"\n                  (ngModelChange)=\"\n                    updateCertificate(trustedCertificate, { autoRegistrationEnabled: $event })\n                  \"\n                />\n                <span></span>\n                <span> {{ 'Auto registration' | translate }}</span>\n              </label>\n            </c8y-form-group>\n          </div>\n        </div>\n      </div>\n    </c8y-li-collapse>\n  </c8y-li>\n</c8y-list-group>\n"
            },] }
];
TrustedCertificatesComponent.ctorParameters = () => [
    { type: BsModalService },
    { type: AlertService },
    { type: TrustedCertificateService },
    { type: ModalService },
    { type: TranslateService }
];
//# sourceMappingURL=data:application/json;base64, 