import { Component, ElementRef, EventEmitter, HostListener, Input, Output, ViewChild } from '@angular/core';
import { FormBuilder, Validators } from '@angular/forms';
import { AlertService, C8yStepper, GainsightService, gettext, Permissions } from '@c8y/ngx-components';
import { PRODUCT_EXPERIENCE_SUB_ASSETS_SHARED } from '../shared/sub-assets.model';
import { SubAssetsService } from '../sub-assets.service';
import { AddGroupService } from './add-group.service';
import * as i0 from "@angular/core";
import * as i1 from "@angular/forms";
import * as i2 from "./add-group.service";
import * as i3 from "@c8y/ngx-components";
import * as i4 from "../sub-assets.service";
import * as i5 from "@angular/common";
import * as i6 from "@angular/cdk/stepper";
import * as i7 from "@c8y/ngx-components/device-grid";
export class AddGroupComponent {
    constructor(fb, addGroupService, alert, subAssetsService, gainsightService, permissionsService) {
        this.fb = fb;
        this.addGroupService = addGroupService;
        this.alert = alert;
        this.subAssetsService = subAssetsService;
        this.gainsightService = gainsightService;
        this.permissionsService = permissionsService;
        this.refresh = new EventEmitter();
        this.onDeviceQueryStringChange = new EventEmitter();
        this.onCancel = new EventEmitter();
        this.pendingStatus = false;
        this.pagination = { pageSize: 20, currentPage: 1 };
        this.selected = [];
        this.canCreateGroup = false;
        this.canAssignDevice = false;
        this.PRODUCT_EXPERIENCE = PRODUCT_EXPERIENCE_SUB_ASSETS_SHARED;
        this.ITEMS_SELECT_LIMIT = 15;
        this.btnLabels = {
            next: gettext('Next'),
            cancel: gettext('Cancel'),
            create: gettext('Create')
        };
    }
    onEnterKeyDown(_event) {
        // Order matters! Needs to be placed before this.stepper.next
        if ((this.isGroupDetailsStep() && !this.canAssignDevice) || this.isAssignDeviceStep()) {
            this.createGroup();
            return;
        }
        this.stepper.next();
    }
    async ngOnInit() {
        this.formGroupStepOne = this.fb.group({
            name: ['', Validators.required],
            description: ['']
        });
        this.subscription = this.onCancel.subscribe(() => this.resetStepper());
        this.canCreateGroup =
            this.subAssetsService.canCreateGroup() ||
                (await this.permissionsService.canEdit([
                    Permissions.ROLE_INVENTORY_ADMIN,
                    Permissions.ROLE_INVENTORY_CREATE,
                    Permissions.ROLE_MANAGED_OBJECT_ADMIN,
                    Permissions.ROLE_MANAGED_OBJECT_CREATE
                ], {
                    id: this.currentGroupId
                }));
        this.canAssignDevice = await this.subAssetsService.canAssignDevice({
            id: this.currentGroupId
        });
    }
    ngAfterViewInit() {
        this.nameInput = this.nameInputRef.nativeElement;
        this.setFocusOnNameInput();
    }
    async createGroup() {
        if (this.canCreateGroup === false) {
            return;
        }
        this.pendingStatus = true;
        await this.addGroupService.createGroupAndAssignDevices(this.formGroupStepOne.value, this.currentGroupId, this.selected);
        this.pendingStatus = false;
        this.resetStepper();
        const alertMsg = gettext('Group created.');
        this.gainsightService.triggerEvent(PRODUCT_EXPERIENCE_SUB_ASSETS_SHARED.EVENT, {
            component: PRODUCT_EXPERIENCE_SUB_ASSETS_SHARED.ADD_GROUP.COMPONENTS.ADD_GROUP,
            url: window.location.href,
            result: PRODUCT_EXPERIENCE_SUB_ASSETS_SHARED.ADD_GROUP.RESULTS.ADD_SUCCESS
        });
        this.alert.success(alertMsg);
        this.refresh.emit();
        this.onCancel.emit();
    }
    onSelected(selectedDevicesIDs) {
        this.selected = selectedDevicesIDs;
    }
    resetStepper() {
        this.stepper.reset();
        this.stepper.selectedIndex = 1;
        this.selected = [];
    }
    ngOnDestroy() {
        if (this.subscription) {
            this.subscription.unsubscribe();
        }
    }
    isGroupDetailsStep() {
        return this.stepper.selectedIndex === 0;
    }
    isAssignDeviceStep() {
        return this.stepper.selectedIndex === 1;
    }
    setFocusOnNameInput() {
        if (this.nameInput) {
            this.nameInput.focus();
            this.nameInput.select();
        }
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "18.2.9", ngImport: i0, type: AddGroupComponent, deps: [{ token: i1.FormBuilder }, { token: i2.AddGroupService }, { token: i3.AlertService }, { token: i4.SubAssetsService }, { token: i3.GainsightService }, { token: i3.Permissions }], target: i0.ɵɵFactoryTarget.Component }); }
    static { this.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "18.2.9", type: AddGroupComponent, selector: "c8y-add-group", inputs: { currentGroupId: "currentGroupId", refresh: "refresh" }, outputs: { onDeviceQueryStringChange: "onDeviceQueryStringChange", onCancel: "onCancel" }, host: { listeners: { "document:keydown.enter": "onEnterKeyDown($event)" } }, viewQueries: [{ propertyName: "stepper", first: true, predicate: C8yStepper, descendants: true }, { propertyName: "nameInputRef", first: true, predicate: ["nameRef"], descendants: true }], ngImport: i0, template: "<div class=\"d-contents\" *ngIf=\"!currentGroupId; else stepper\">\n  <ng-container [ngTemplateOutlet]=\"stepper\"></ng-container>\n</div>\n\n<ng-template #stepper>\n  <c8y-stepper\n    class=\"d-col flex-nowrap no-align-items fit-h c8y-stepper--no-btns\"\n    [disableDefaultIcons]=\"{ edit: true, done: false }\"\n    [customClasses]=\"['col-md-6', 'col-md-offset-3', 'm-t-24', 'm-b-40', 'p-0', 'flex-no-shrink']\"\n    linear\n    c8yProductExperience\n    inherit\n    [actionName]=\"PRODUCT_EXPERIENCE.EVENT\"\n    [actionData]=\"{ component: PRODUCT_EXPERIENCE.ADD_GROUP.COMPONENTS.ADD_GROUP }\"\n  >\n    <cdk-step [stepControl]=\"formGroupStepOne\" [label]=\"'New group' | translate\">\n      <div class=\"p-16 p-t-0 flex-no-shrink separator-bottom col-xs-12\">\n        <div class=\"row\">\n          <div class=\"col-md-6 col-md-offset-3 col-lg-4 col-lg-offset-4\">\n            <div class=\"h4 text-center text-medium\">\n              {{ 'New group' | translate }}\n            </div>\n          </div>\n        </div>\n      </div>\n      <div class=\"col-xs-12 flex-grow no-gutter\">\n        <div class=\"card-inner-scroll fit-h\">\n          <div class=\"card-block p-b-0\">\n            <div class=\"row\">\n              <div class=\"col-md-6 col-md-offset-3 col-lg-4 col-lg-offset-4\">\n                <c8y-form-group [novalidation]=\"true\">\n                  <div [formGroup]=\"formGroupStepOne\">\n                    <c8y-form-group>\n                      <label translate>Name</label>\n                      <input\n                        class=\"form-control\"\n                        type=\"text\"\n                        formControlName=\"name\"\n                        placeholder=\"{{ 'e.g. First floor' | translate }} \"\n                        maxlength=\"254\"\n                        #nameRef\n                        required\n                      />\n                    </c8y-form-group>\n\n                    <c8y-form-group>\n                      <label translate>Description</label>\n                      <input\n                        class=\"form-control\"\n                        type=\"text\"\n                        formControlName=\"description\"\n                        placeholder=\"{{ 'e.g. first floor devices' | translate }}\"\n                      />\n                    </c8y-form-group>\n                  </div>\n                </c8y-form-group>\n                <c8y-form-group>\n                  <div [formGroup]=\"formGroupStepOne\"></div>\n                </c8y-form-group>\n                <div class=\"alert alert-info max-width-100\" translate *ngIf=\"!canAssignDevice\">\n                  You don't have permission to assign devices.\n                </div>\n              </div>\n            </div>\n          </div>\n        </div>\n      </div>\n\n      <c8y-stepper-buttons\n        class=\"d-block card-footer p-24 separator\"\n        (onCancel)=\"onCancel.emit()\"\n        (onCustom)=\"createGroup()\"\n        [disabled]=\"!canCreateGroup\"\n        [labels]=\"\n          canAssignDevice\n            ? { next: btnLabels.next, cancel: btnLabels.cancel }\n            : { custom: btnLabels.create, cancel: btnLabels.cancel }\n        \"\n        [showButtons]=\"\n          canAssignDevice ? { next: true, cancel: true } : { custom: true, cancel: true }\n        \"\n      ></c8y-stepper-buttons>\n    </cdk-step>\n    <cdk-step [label]=\"'Assign devices' | translate\">\n      <div class=\"p-16 p-t-0 flex-no-shrink separator-bottom col-xs-12\">\n        <div class=\"row\">\n          <div class=\"col-md-6 col-md-offset-3 col-lg-4 col-lg-offset-4\">\n            <div class=\"h4 text-center text-medium\">\n              {{ 'Assign devices' | translate }}\n            </div>\n          </div>\n        </div>\n      </div>\n      <div class=\"col-xs-12 no-gutter flex-grow\">\n        <c8y-device-grid\n          [title]=\"'Select target devices' | translate\"\n          [actionControls]=\"[]\"\n          [infiniteScroll]=\"'auto'\"\n          [selectable]=\"true\"\n          [pagination]=\"pagination\"\n          (itemsSelect)=\"onSelected($event)\"\n          [refresh]=\"refresh\"\n          c8yProductExperience\n          [actionName]=\"PRODUCT_EXPERIENCE.EVENT\"\n          [actionData]=\"{ component: PRODUCT_EXPERIENCE.ADD_GROUP.COMPONENTS.ADD_GROUP }\"\n        ></c8y-device-grid>\n      </div>\n      <c8y-stepper-buttons\n        class=\"d-block card-footer p-24 separator\"\n        (onCancel)=\"onCancel.emit()\"\n        (onCustom)=\"createGroup()\"\n        [labels]=\"{ custom: btnLabels.create }\"\n        [disabled]=\"!canAssignDevice\"\n        [pending]=\"pendingStatus\"\n      ></c8y-stepper-buttons>\n    </cdk-step>\n  </c8y-stepper>\n</ng-template>\n", dependencies: [{ kind: "directive", type: i3.C8yTranslateDirective, selector: "[translate],[ngx-translate]" }, { kind: "directive", type: i5.NgIf, selector: "[ngIf]", inputs: ["ngIf", "ngIfThen", "ngIfElse"] }, { kind: "directive", type: i5.NgTemplateOutlet, selector: "[ngTemplateOutlet]", inputs: ["ngTemplateOutletContext", "ngTemplateOutlet", "ngTemplateOutletInjector"] }, { kind: "directive", type: i1.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: i1.NgControlStatus, selector: "[formControlName],[ngModel],[formControl]" }, { kind: "directive", type: i1.NgControlStatusGroup, selector: "[formGroupName],[formArrayName],[ngModelGroup],[formGroup],form:not([ngNoForm]),[ngForm]" }, { kind: "directive", type: i1.RequiredValidator, selector: ":not([type=checkbox])[required][formControlName],:not([type=checkbox])[required][formControl],:not([type=checkbox])[required][ngModel]", inputs: ["required"] }, { kind: "directive", type: i1.MaxLengthValidator, selector: "[maxlength][formControlName],[maxlength][formControl],[maxlength][ngModel]", inputs: ["maxlength"] }, { kind: "component", type: i3.FormGroupComponent, selector: "c8y-form-group", inputs: ["hasError", "hasWarning", "hasSuccess", "novalidation", "status"] }, { kind: "directive", type: i3.RequiredInputPlaceholderDirective, selector: "input[required], input[formControlName]" }, { kind: "component", type: i3.C8yStepper, selector: "c8y-stepper", inputs: ["disableDefaultIcons", "disableProgressButtons", "customClasses", "hideStepProgress", "useStepLabelsAsTitlesOnly"], outputs: ["onStepChange"] }, { kind: "component", type: i6.CdkStep, selector: "cdk-step", inputs: ["stepControl", "label", "errorMessage", "aria-label", "aria-labelledby", "state", "editable", "optional", "completed", "hasError"], outputs: ["interacted"], exportAs: ["cdkStep"] }, { kind: "component", type: i3.C8yStepperButtons, selector: "c8y-stepper-buttons", inputs: ["labels", "pending", "disabled", "showButtons"], outputs: ["onCancel", "onNext", "onBack", "onCustom"] }, { kind: "directive", type: i3.ProductExperienceDirective, selector: "[c8yProductExperience]", inputs: ["actionName", "actionData", "inherit", "suppressDataOverriding"] }, { kind: "directive", type: i1.FormGroupDirective, selector: "[formGroup]", inputs: ["formGroup"], outputs: ["ngSubmit"], exportAs: ["ngForm"] }, { kind: "directive", type: i1.FormControlName, selector: "[formControlName]", inputs: ["formControlName", "disabled", "ngModel"], outputs: ["ngModelChange"] }, { kind: "component", type: i7.DeviceGridComponent, selector: "c8y-device-grid", inputs: ["dataCallback", "refresh", "title", "loadMoreItemsLabel", "loadingItemsLabel", "legacyConfigKey", "legacyFilterKey", "columns", "pagination", "infiniteScroll", "actionControls", "selectable", "singleSelection", "baseQuery", "bulkActionControls", "headerActionControls", "childDeviceGrid", "parentDeviceId", "withChildren", "showSearch", "activeClassName"], outputs: ["onColumnsChange", "onFilterChange", "onDeviceQueryStringChange", "itemsSelect"] }, { kind: "pipe", type: i3.C8yTranslatePipe, name: "translate" }] }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "18.2.9", ngImport: i0, type: AddGroupComponent, decorators: [{
            type: Component,
            args: [{ selector: 'c8y-add-group', template: "<div class=\"d-contents\" *ngIf=\"!currentGroupId; else stepper\">\n  <ng-container [ngTemplateOutlet]=\"stepper\"></ng-container>\n</div>\n\n<ng-template #stepper>\n  <c8y-stepper\n    class=\"d-col flex-nowrap no-align-items fit-h c8y-stepper--no-btns\"\n    [disableDefaultIcons]=\"{ edit: true, done: false }\"\n    [customClasses]=\"['col-md-6', 'col-md-offset-3', 'm-t-24', 'm-b-40', 'p-0', 'flex-no-shrink']\"\n    linear\n    c8yProductExperience\n    inherit\n    [actionName]=\"PRODUCT_EXPERIENCE.EVENT\"\n    [actionData]=\"{ component: PRODUCT_EXPERIENCE.ADD_GROUP.COMPONENTS.ADD_GROUP }\"\n  >\n    <cdk-step [stepControl]=\"formGroupStepOne\" [label]=\"'New group' | translate\">\n      <div class=\"p-16 p-t-0 flex-no-shrink separator-bottom col-xs-12\">\n        <div class=\"row\">\n          <div class=\"col-md-6 col-md-offset-3 col-lg-4 col-lg-offset-4\">\n            <div class=\"h4 text-center text-medium\">\n              {{ 'New group' | translate }}\n            </div>\n          </div>\n        </div>\n      </div>\n      <div class=\"col-xs-12 flex-grow no-gutter\">\n        <div class=\"card-inner-scroll fit-h\">\n          <div class=\"card-block p-b-0\">\n            <div class=\"row\">\n              <div class=\"col-md-6 col-md-offset-3 col-lg-4 col-lg-offset-4\">\n                <c8y-form-group [novalidation]=\"true\">\n                  <div [formGroup]=\"formGroupStepOne\">\n                    <c8y-form-group>\n                      <label translate>Name</label>\n                      <input\n                        class=\"form-control\"\n                        type=\"text\"\n                        formControlName=\"name\"\n                        placeholder=\"{{ 'e.g. First floor' | translate }} \"\n                        maxlength=\"254\"\n                        #nameRef\n                        required\n                      />\n                    </c8y-form-group>\n\n                    <c8y-form-group>\n                      <label translate>Description</label>\n                      <input\n                        class=\"form-control\"\n                        type=\"text\"\n                        formControlName=\"description\"\n                        placeholder=\"{{ 'e.g. first floor devices' | translate }}\"\n                      />\n                    </c8y-form-group>\n                  </div>\n                </c8y-form-group>\n                <c8y-form-group>\n                  <div [formGroup]=\"formGroupStepOne\"></div>\n                </c8y-form-group>\n                <div class=\"alert alert-info max-width-100\" translate *ngIf=\"!canAssignDevice\">\n                  You don't have permission to assign devices.\n                </div>\n              </div>\n            </div>\n          </div>\n        </div>\n      </div>\n\n      <c8y-stepper-buttons\n        class=\"d-block card-footer p-24 separator\"\n        (onCancel)=\"onCancel.emit()\"\n        (onCustom)=\"createGroup()\"\n        [disabled]=\"!canCreateGroup\"\n        [labels]=\"\n          canAssignDevice\n            ? { next: btnLabels.next, cancel: btnLabels.cancel }\n            : { custom: btnLabels.create, cancel: btnLabels.cancel }\n        \"\n        [showButtons]=\"\n          canAssignDevice ? { next: true, cancel: true } : { custom: true, cancel: true }\n        \"\n      ></c8y-stepper-buttons>\n    </cdk-step>\n    <cdk-step [label]=\"'Assign devices' | translate\">\n      <div class=\"p-16 p-t-0 flex-no-shrink separator-bottom col-xs-12\">\n        <div class=\"row\">\n          <div class=\"col-md-6 col-md-offset-3 col-lg-4 col-lg-offset-4\">\n            <div class=\"h4 text-center text-medium\">\n              {{ 'Assign devices' | translate }}\n            </div>\n          </div>\n        </div>\n      </div>\n      <div class=\"col-xs-12 no-gutter flex-grow\">\n        <c8y-device-grid\n          [title]=\"'Select target devices' | translate\"\n          [actionControls]=\"[]\"\n          [infiniteScroll]=\"'auto'\"\n          [selectable]=\"true\"\n          [pagination]=\"pagination\"\n          (itemsSelect)=\"onSelected($event)\"\n          [refresh]=\"refresh\"\n          c8yProductExperience\n          [actionName]=\"PRODUCT_EXPERIENCE.EVENT\"\n          [actionData]=\"{ component: PRODUCT_EXPERIENCE.ADD_GROUP.COMPONENTS.ADD_GROUP }\"\n        ></c8y-device-grid>\n      </div>\n      <c8y-stepper-buttons\n        class=\"d-block card-footer p-24 separator\"\n        (onCancel)=\"onCancel.emit()\"\n        (onCustom)=\"createGroup()\"\n        [labels]=\"{ custom: btnLabels.create }\"\n        [disabled]=\"!canAssignDevice\"\n        [pending]=\"pendingStatus\"\n      ></c8y-stepper-buttons>\n    </cdk-step>\n  </c8y-stepper>\n</ng-template>\n" }]
        }], ctorParameters: () => [{ type: i1.FormBuilder }, { type: i2.AddGroupService }, { type: i3.AlertService }, { type: i4.SubAssetsService }, { type: i3.GainsightService }, { type: i3.Permissions }], propDecorators: { currentGroupId: [{
                type: Input
            }], refresh: [{
                type: Input
            }], onDeviceQueryStringChange: [{
                type: Output
            }], onCancel: [{
                type: Output
            }], stepper: [{
                type: ViewChild,
                args: [C8yStepper, { static: false }]
            }], nameInputRef: [{
                type: ViewChild,
                args: ['nameRef', { static: false }]
            }], onEnterKeyDown: [{
                type: HostListener,
                args: ['document:keydown.enter', ['$event']]
            }] } });
//# sourceMappingURL=data:application/json;base64, 