import { Component , EventEmitter , Input , Output } from '@angular/core' ; import { CmdbType } from '../../../models/cmdb-type' ; import { CmdbMode } from '../../../modes.enum' ; import { Group } from '../../../../management/models/group' ; import { User } from '../../../../management/models/user' ; import { FormControl , FormGroup } from '@angular/forms' ; import { ReplaySubject } from 'rxjs' ; import { takeUntil } from 'rxjs/operators' ; import { nameConvention } from '../../../../layout/directives/name.directive' ; @ Component ( { template : `` } ) export abstract class ConfigEditBaseComponent { protected abstract subscriber : ReplaySubject < void > ; /**
     * Cmdb modes for template usage.
     */ public MODES = CmdbMode ; @ Input ( ) public mode : CmdbMode = CmdbMode . Create ; @ Input ( ) public form : FormGroup ; public abstract nameControl : FormControl ; public abstract labelControl : FormControl ; @ Input ( ) public data : any ; @ Input ( ) public sections : Array < any > ; @ Input ( ) public fields : Array < any > = [ ] ; @ Input ( ) public types : Array < CmdbType > = [ ] ; @ Input ( ) public groups : Array < Group > = [ ] ; @ Input ( ) public users : Array < User > = [ ] ; protected constructor ( ) { this . form = new FormGroup ( { } ) ; } protected disableControlOnEdit ( control ) { if ( this . mode === CmdbMode . Edit ) { control . disable ( { onlySelf : false , emitEvent : false } ) ; } } public onInputChange ( change , idx ) { this . data [ idx ] = change ; } protected validateNameLabelControl ( nameControl , labelControl , subscriber ) { this . disableControlOnEdit ( nameControl ) ; if ( this . mode === CmdbMode . Create ) { labelControl . valueChanges . pipe ( takeUntil ( subscriber ) ) . subscribe ( ( changes ) => { if ( ! nameControl . touched ) { nameControl . setValue ( nameConvention ( changes ) , { emitEvent : true } ) ; } } ) ; } } protected patchData ( data , form ) { form . patchValue ( data ) ; if ( this . mode === CmdbMode . Edit ) { this . form . markAllAsTouched ( ) ; } } public calculateName ( value ) { if ( this . mode !== CmdbMode . Edit ) { this . data . name = value . replace ( / /g , '-' ) . toLowerCase ( ) ; this . data . name = this . data . name . replace ( /[^a-z0-9 \-]/gi , '' ) . toLowerCase ( ) ; } if ( ! this . checkNameUniqueness ( ) ) { this . calculateName ( this . data . name += '-1' ) ; } } private checkNameUniqueness ( ) { const { type , name } = this . data ; switch ( type ) { case 'section' : return this . sections . filter ( el => el . name === name ) . length <= 1 ; default : let count = 0 ; this . sections . forEach ( ( sec ) => { count += sec . fields . filter ( el => el . name === name ) . length ; } ) ; return count <= 1 ; } } }