import * as i0 from '@angular/core';
import { Input, Component, Injectable } from '@angular/core';
import * as i1 from '@c8y/ngx-components/branding/shared/data';
import * as i2 from '@angular/forms';
import { Validators, ReactiveFormsModule } from '@angular/forms';
import { ModalComponent, IconDirective, FormGroupComponent, MessagesComponent, MessageDirective, C8yTranslateDirective, C8yTranslatePipe } from '@c8y/ngx-components';
import { gettext } from '@c8y/ngx-components/gettext';
import { NgForOf } from '@angular/common';
import * as i1$1 from 'ngx-bootstrap/modal';

class AddBrandingModalComponent {
    constructor(branding, formBuilder) {
        this.branding = branding;
        this.formBuilder = formBuilder;
        this.duplicateBranding = false;
        this.namesAlreadyTaken = [];
        this.loading = true;
        this.result = new Promise((resolve, reject) => {
            this._resovle = resolve;
            this._reject = reject;
        });
        this.messages = [
            {
                name: 'nameAlreadyTaken',
                text: gettext('The provided name is already taken.')
            },
            {
                name: 'onlyLowerCaseCharacters',
                text: gettext('Only lower case characters are allowed.')
            },
            {
                name: 'shouldStartWithLowerCaseLetterOrNumber',
                text: gettext('Should start with a lower case letter or a number.')
            },
            {
                name: 'invalidCharacters',
                text: gettext('Invalid character "{{ invalidCharacter }}". Only a-z, 0-9 and - are allowed.')
            }
        ];
        this.form = this.initForm();
        this.getExistingBrandingVersions();
    }
    async getExistingBrandingVersions() {
        try {
            const { variants } = await this.branding.loadBrandingVariants();
            this.namesAlreadyTaken = variants.map(variant => variant.version);
        }
        catch (e) {
            console.warn(e);
        }
        this.loading = false;
    }
    initForm() {
        return this.formBuilder.group({
            brandingName: [
                '',
                [Validators.required, this.ensureProperVariantName(), this.ensureNotExistingName()]
            ]
        });
    }
    cancel() {
        this._reject();
    }
    save() {
        this._resovle(this.form.value);
    }
    ensureNotExistingName() {
        return (control) => {
            if (typeof control.value === 'string') {
                const lowercaseName = control.value.toLowerCase();
                const nameAlreadyTaken = this.namesAlreadyTaken.some(name => name.toLowerCase().startsWith(lowercaseName + '-'));
                if (nameAlreadyTaken) {
                    return { nameAlreadyTaken: {} };
                }
            }
            return null;
        };
    }
    ensureProperVariantName() {
        return (control) => {
            if (typeof control.value === 'string') {
                const value = control.value;
                if (/[A-Z]/.test(value)) {
                    return {
                        onlyLowerCaseCharacters: {}
                    };
                }
                if (!/^[a-z0-9]+/.test(value)) {
                    return {
                        shouldStartWithLowerCaseLetterOrNumber: {}
                    };
                }
                const matches = /[^a-z0-9-]/.exec(value);
                if (matches) {
                    return {
                        invalidCharacters: {
                            invalidCharacter: matches[0]
                        }
                    };
                }
            }
            return null;
        };
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: AddBrandingModalComponent, deps: [{ token: i1.StoreBrandingService }, { token: i2.FormBuilder }], target: i0.ɵɵFactoryTarget.Component }); }
    static { this.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "20.3.19", type: AddBrandingModalComponent, isStandalone: true, selector: "c8y-add-branding-modal", inputs: { duplicateBranding: "duplicateBranding" }, ngImport: i0, template: "<c8y-modal\n  [title]=\"duplicateBranding ? 'Duplicate Branding' : 'Create Branding'\"\n  [headerClasses]=\"'dialog-header'\"\n  (onDismiss)=\"cancel()\"\n  (onClose)=\"save()\"\n  [disabled]=\"form.invalid\"\n  [labels]=\"{ cancel: 'Cancel', ok: 'Save' }\"\n>\n<ng-container c8y-modal-title>\n  <span [c8yIcon]=\"'palette'\"></span>\n</ng-container>\n  <div [formGroup]=\"form\" class=\"p-24\">\n    <c8y-form-group>\n      <label\n        for=\"brandingName\"\n        translate\n      >\n        Branding name\n      </label>\n      <input\n        class=\"form-control\"\n        name=\"brandingName\"\n        id=\"brandingName\"\n        type=\"text\"\n        formControlName=\"brandingName\"\n        placeholder=\"{{'e.g. {{ example }}' | translate : { example: 'main-branding' } }}\"\n      />\n      <c8y-messages [helpMessage]=\"'Upper case letters not allowed' | translate\">\n        <c8y-message *ngFor=\"let message of messages\"\n          [name]=\"message.name\"\n          [text]=\"message.text | translate\"\n        ></c8y-message>\n      </c8y-messages>\n    </c8y-form-group>\n  </div>\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: "component", type: FormGroupComponent, selector: "c8y-form-group", inputs: ["hasError", "hasWarning", "hasSuccess", "novalidation", "status"] }, { kind: "component", type: MessagesComponent, selector: "c8y-messages", inputs: ["show", "defaults", "helpMessage"] }, { kind: "directive", type: MessageDirective, selector: "c8y-message", inputs: ["name", "text"] }, { kind: "directive", type: C8yTranslateDirective, selector: "[translate],[ngx-translate]" }, { kind: "directive", type: NgForOf, selector: "[ngFor][ngForOf]", inputs: ["ngForOf", "ngForTrackBy", "ngForTemplate"] }, { kind: "ngmodule", type: ReactiveFormsModule }, { kind: "directive", type: i2.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: i2.NgControlStatus, selector: "[formControlName],[ngModel],[formControl]" }, { kind: "directive", type: i2.NgControlStatusGroup, selector: "[formGroupName],[formArrayName],[ngModelGroup],[formGroup],form:not([ngNoForm]),[ngForm]" }, { kind: "directive", type: i2.FormGroupDirective, selector: "[formGroup]", inputs: ["formGroup"], outputs: ["ngSubmit"], exportAs: ["ngForm"] }, { kind: "directive", type: i2.FormControlName, selector: "[formControlName]", inputs: ["formControlName", "disabled", "ngModel"], outputs: ["ngModelChange"] }, { kind: "pipe", type: C8yTranslatePipe, name: "translate" }] }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: AddBrandingModalComponent, decorators: [{
            type: Component,
            args: [{ selector: 'c8y-add-branding-modal', standalone: true, imports: [
                        ModalComponent,
                        IconDirective,
                        FormGroupComponent,
                        MessagesComponent,
                        MessageDirective,
                        C8yTranslateDirective,
                        C8yTranslatePipe,
                        NgForOf,
                        ReactiveFormsModule
                    ], template: "<c8y-modal\n  [title]=\"duplicateBranding ? 'Duplicate Branding' : 'Create Branding'\"\n  [headerClasses]=\"'dialog-header'\"\n  (onDismiss)=\"cancel()\"\n  (onClose)=\"save()\"\n  [disabled]=\"form.invalid\"\n  [labels]=\"{ cancel: 'Cancel', ok: 'Save' }\"\n>\n<ng-container c8y-modal-title>\n  <span [c8yIcon]=\"'palette'\"></span>\n</ng-container>\n  <div [formGroup]=\"form\" class=\"p-24\">\n    <c8y-form-group>\n      <label\n        for=\"brandingName\"\n        translate\n      >\n        Branding name\n      </label>\n      <input\n        class=\"form-control\"\n        name=\"brandingName\"\n        id=\"brandingName\"\n        type=\"text\"\n        formControlName=\"brandingName\"\n        placeholder=\"{{'e.g. {{ example }}' | translate : { example: 'main-branding' } }}\"\n      />\n      <c8y-messages [helpMessage]=\"'Upper case letters not allowed' | translate\">\n        <c8y-message *ngFor=\"let message of messages\"\n          [name]=\"message.name\"\n          [text]=\"message.text | translate\"\n        ></c8y-message>\n      </c8y-messages>\n    </c8y-form-group>\n  </div>\n</c8y-modal>\n" }]
        }], ctorParameters: () => [{ type: i1.StoreBrandingService }, { type: i2.FormBuilder }], propDecorators: { duplicateBranding: [{
                type: Input
            }] } });

class AddBrandingModalService {
    constructor(modal) {
        this.modal = modal;
    }
    async openAddBrandingModal() {
        let versionDetails;
        try {
            const modalRef = this.modal.show(AddBrandingModalComponent, {
                class: 'modal-sm',
                ariaDescribedby: 'modal-body',
                ariaLabelledBy: 'modal-title',
                ignoreBackdropClick: true,
                keyboard: false
            });
            versionDetails = await modalRef.content.result;
        }
        catch (e) {
            // modal closed
            return;
        }
        return versionDetails;
    }
    async openDuplicateBrandingModal() {
        let versionDetails;
        try {
            const modalRef = this.modal.show(AddBrandingModalComponent, {
                class: 'modal-sm',
                ariaDescribedby: 'modal-body',
                ariaLabelledBy: 'modal-title',
                initialState: { duplicateBranding: true },
                ignoreBackdropClick: true,
                keyboard: false
            });
            versionDetails = await modalRef.content.result;
        }
        catch (e) {
            // modal closed
            return;
        }
        return versionDetails;
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: AddBrandingModalService, deps: [{ token: i1$1.BsModalService }], target: i0.ɵɵFactoryTarget.Injectable }); }
    static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: AddBrandingModalService, providedIn: 'root' }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: AddBrandingModalService, decorators: [{
            type: Injectable,
            args: [{
                    providedIn: 'root'
                }]
        }], ctorParameters: () => [{ type: i1$1.BsModalService }] });

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

export { AddBrandingModalComponent, AddBrandingModalService };
//# sourceMappingURL=c8y-ngx-components-branding-shared-lazy-add-branding-modal.mjs.map
