Update base types based on model
[sdc.git] / catalog-ui / src / app / view-models / workspace / tabs / general / general-view-model.ts
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 'use strict';
22 import * as _ from "lodash";
23 import {Dictionary} from "lodash";
24 import {
25     ComponentFactory,
26     ComponentState,
27     ComponentType,
28     DEFAULT_ICON,
29     EVENTS,
30     instantiationType,
31     ModalsHandler,
32     ResourceType,
33     ValidationUtils
34 } from "app/utils";
35 import {EventListenerService, ProgressService} from "app/services";
36 import {CacheService, ElementService, ModelService, ImportVSPService, OnboardingService} from "app/services-ng2";
37 import {Component, IAppConfigurtaion, ICsarComponent, IMainCategory, IMetadataKey, ISubCategory, IValidate, Resource, Service} from "app/models";
38 import {IWorkspaceViewModelScope} from "app/view-models/workspace/workspace-view-model";
39 import {CATEGORY_SERVICE_METADATA_KEYS, PREVIOUS_CSAR_COMPONENT} from "../../../../utils/constants";
40 import {Observable} from "rxjs";
41 import {Model} from "../../../../models/model";
42
43 export class Validation {
44     componentNameValidationPattern:RegExp;
45     contactIdValidationPattern:RegExp;
46     tagValidationPattern:RegExp;
47     VendorReleaseValidationPattern:RegExp;
48     VendorNameValidationPattern:RegExp;
49     VendorModelNumberValidationPattern:RegExp;
50     commentValidationPattern:RegExp;
51 }
52
53 export class componentCategories {//categories field bind to this obj in order to solve this bug: DE242059
54     selectedCategory:string;
55 }
56
57 export class componentModel {
58     selectedModel:string;
59 }
60
61 export interface IEnvironmentContext {
62     defaultValue:string;
63     validValues:Array<string>;
64 }
65
66 export interface IGeneralScope extends IWorkspaceViewModelScope {
67     validation:Validation;
68     editForm:ng.IFormController;
69     categories:Array<IMainCategory>;
70     environmentContextObj:IEnvironmentContext;
71     latestCategoryId:string;
72     latestVendorName:string;
73     importedFileExtension:any;
74     isCreate:boolean;
75     isShowFileBrowse:boolean;
76     isShowOnboardingSelectionBrowse:boolean;
77     importedToscaBrowseFileText:string;
78     importCsarProProgressKey:string;
79     browseFileLabel:string;
80     componentCategories:componentCategories;
81     componentModel:componentModel;
82     instantiationTypes:Array<instantiationType>;
83     isHiddenCategorySelected: boolean;
84
85     save():Promise<any>;
86     revert():void;
87     onImportFileChange():void;
88     validateField(field:any):boolean;
89     validateName(isInit:boolean):void;
90     calculateUnique(mainCategory:string, subCategory:string):string; // Build unique string from main and sub category
91     onVendorNameChange(oldVendorName:string):void;
92     convertCategoryStringToOneArray(category:string, subcategory:string):Array<IMainCategory>;
93     onCategoryChange():void;
94     onEcompGeneratedNamingChange():void;
95     onBaseTypeChange():void;
96     openOnBoardingModal():void;
97     initCategoreis():void;
98     initEnvironmentContext():void;
99     initInstantiationTypes():void;
100     initBaseTypes():void;
101     onInstantiationTypeChange():void;
102     updateIcon():void;
103     possibleToUpdateIcon():boolean;
104     initModel():void;
105 }
106
107 // tslint:disable-next-line:max-classes-per-file
108 export class GeneralViewModel {
109
110     static '$inject' = [
111         '$scope',
112         'Sdc.Services.CacheService',
113         'ComponentNameValidationPattern',
114         'ContactIdValidationPattern',
115         'TagValidationPattern',
116         'VendorReleaseValidationPattern',
117         'VendorNameValidationPattern',
118         'VendorModelNumberValidationPattern',
119         'CommentValidationPattern',
120         'ValidationUtils',
121         'sdcConfig',
122         '$state',
123         'ModalsHandler',
124         'EventListenerService',
125         'Notification',
126         'Sdc.Services.ProgressService',
127         '$interval',
128         '$filter',
129         '$timeout',
130         'OnboardingService',
131         'ComponentFactory',
132         'ImportVSPService',
133         'ElementService',
134         'ModelService',
135         '$stateParams'
136     ];
137
138     constructor(private $scope:IGeneralScope,
139                 private cacheService:CacheService,
140                 private ComponentNameValidationPattern:RegExp,
141                 private ContactIdValidationPattern:RegExp,
142                 private TagValidationPattern:RegExp,
143                 private VendorReleaseValidationPattern:RegExp,
144                 private VendorNameValidationPattern:RegExp,
145                 private VendorModelNumberValidationPattern:RegExp,
146                 private CommentValidationPattern:RegExp,
147                 private ValidationUtils:ValidationUtils,
148                 private sdcConfig:IAppConfigurtaion,
149                 private $state:ng.ui.IStateService,
150                 private ModalsHandler:ModalsHandler,
151                 private EventListenerService:EventListenerService,
152                 private Notification:any,
153                 private progressService:ProgressService,
154                 protected $interval:any,
155                 private $filter:ng.IFilterService,
156                 private $timeout:ng.ITimeoutService,
157                 private onBoardingService: OnboardingService,
158                 private ComponentFactory:ComponentFactory,
159                 private importVSPService: ImportVSPService,
160                 private elementService: ElementService,
161                 private modelService: ModelService,
162                 private $stateParams: any) {
163
164         this.initScopeValidation();
165         this.initScopeMethods();
166         this.initScope();
167     }
168
169
170
171
172     private initScopeValidation = ():void => {
173         this.$scope.validation = new Validation();
174         this.$scope.validation.componentNameValidationPattern = this.ComponentNameValidationPattern;
175         this.$scope.validation.contactIdValidationPattern = this.ContactIdValidationPattern;
176         this.$scope.validation.tagValidationPattern = this.TagValidationPattern;
177         this.$scope.validation.VendorReleaseValidationPattern = this.VendorReleaseValidationPattern;
178         this.$scope.validation.VendorNameValidationPattern = this.VendorNameValidationPattern;
179         this.$scope.validation.VendorModelNumberValidationPattern = this.VendorModelNumberValidationPattern;
180         this.$scope.validation.commentValidationPattern = this.CommentValidationPattern;
181     };
182
183     private loadOnboardingFileCache = (): Observable<Dictionary<Dictionary<string>>> => {
184         let onboardCsarFilesMap:Dictionary<Dictionary<string>>;
185         let onSuccess = (vsps:Array<ICsarComponent>) => {
186             onboardCsarFilesMap = {};
187             _.each(vsps, (vsp:ICsarComponent)=>{
188                 onboardCsarFilesMap[vsp.packageId] = onboardCsarFilesMap[vsp.packageId] || {};
189                 onboardCsarFilesMap[vsp.packageId][vsp.version] = vsp.vspName + " (" + vsp.version + ")";
190             });
191             this.cacheService.set('onboardCsarFilesMap', onboardCsarFilesMap);
192             return onboardCsarFilesMap;
193         };
194         let onError = (): void =>{
195             console.log("Error getting onboarding list");
196         };
197         return this.onBoardingService.getOnboardingVSPs().map(onSuccess, onError);
198     };
199
200     private setImportedFileText = ():void => {
201
202         if(!this.$scope.isShowOnboardingSelectionBrowse) return;
203
204         //these variables makes it easier to read this logic
205         let csarUUID:string = (<Resource>this.$scope.component).csarUUID;
206         let csarVersion:string = (<Resource>this.$scope.component).csarVersion;
207
208         let onboardCsarFilesMap:Dictionary<Dictionary<string>> = this.cacheService.get('onboardCsarFilesMap');
209         let assignFileName = ():void => {
210             if(this.$scope.component.vspArchived){
211                 this.$scope.importedToscaBrowseFileText = 'VSP is archived';
212             } else {
213                 if(this.$stateParams.componentCsar && this.$scope.component.lifecycleState === 'NOT_CERTIFIED_CHECKIN' && !this.$scope.isCreateMode()) {
214                     this.$scope.importedToscaBrowseFileText = this.$scope.originComponent.name + ' (' + (this.$scope.originComponent as Resource).csarVersion + ')';
215                 } else {
216                     this.$scope.importedToscaBrowseFileText = onboardCsarFilesMap[csarUUID][csarVersion];
217                 }
218             }
219         }
220
221
222         if(this.$scope.component.vspArchived || (onboardCsarFilesMap && onboardCsarFilesMap[csarUUID] && onboardCsarFilesMap[csarUUID][csarVersion])){ //check that the file name is already in cache
223             assignFileName();
224         } else {
225             this.loadOnboardingFileCache().subscribe((onboardingFiles) => {
226                 onboardCsarFilesMap = onboardingFiles;
227                 this.cacheService.set('onboardCsarFilesMap', onboardingFiles);
228                 assignFileName();
229             }, ()=> {});
230         }
231
232     }
233
234     isCreateModeAvailable(verifyObj:string): boolean {
235         var isCheckout:boolean = ComponentState.NOT_CERTIFIED_CHECKOUT === this.$scope.component.lifecycleState;
236         return this.$scope.isCreateMode() || (isCheckout && !verifyObj)
237     }
238
239     private initScope = ():void => {
240
241         this.$scope.importCsarProgressKey = "importCsarProgressKey";
242
243         this.$scope.browseFileLabel = (this.$scope.component.isResource() && ((<Resource>this.$scope.component).resourceType === ResourceType.VF || (<Resource>this.$scope.component).resourceType === 'SRVC')) ||  this.$scope.component.isService() ? 'Upload File:' : 'Upload VFC:';
244         this.$scope.progressService = this.progressService;
245         this.$scope.componentCategories = new componentCategories();
246         this.$scope.componentCategories.selectedCategory = this.$scope.component.selectedCategory;
247
248
249         // Init UIModel
250         this.$scope.component.tags = _.without(this.$scope.component.tags, this.$scope.component.name);
251
252         // Init categories
253         this.$scope.initCategoreis();
254
255         // Init Environment Context
256         this.$scope.initEnvironmentContext();
257
258         // Init Models
259         this.$scope.initModel();
260
261         // Init the decision if to show file browse.
262         this.$scope.isShowFileBrowse = false;
263         if (this.$scope.component.isResource()) {
264             let resource:Resource = <Resource>this.$scope.component;
265             console.log(resource.name + ": " + resource.csarUUID);
266             if (resource.importedFile) { // Component has imported file.
267                 this.$scope.isShowFileBrowse = true;
268             }
269             if (resource.resourceType === ResourceType.VF && !resource.csarUUID) {
270                 this.$scope.isShowFileBrowse = true;
271             }
272         } else if(this.$scope.component.isService()){
273             let service: Service = <Service>this.$scope.component;
274             console.log(service.name + ": " + service.csarUUID);
275             if (service.importedFile) { // Component has imported file.
276                 this.$scope.isShowFileBrowse = true;
277                 (<Service>this.$scope.component).serviceType = 'Service';
278             }
279             if (this.$scope.isEditMode() && service.serviceType == 'Service' && !service.csarUUID) {
280                 this.$scope.isShowFileBrowse = true;
281             }
282             // Init Instantiation types
283             this.$scope.initInstantiationTypes();
284             this.$scope.initBaseTypes();
285         }
286
287         if (this.cacheService.get(PREVIOUS_CSAR_COMPONENT)) { //keep the old component in the cache until checkout, so we dont need to pass it around
288             this.$scope.setOriginComponent(this.cacheService.get(PREVIOUS_CSAR_COMPONENT));
289             this.cacheService.remove(PREVIOUS_CSAR_COMPONENT);
290         }
291
292         if (this.$stateParams.componentCsar && !this.$scope.isCreateMode()) {
293             this.$scope.updateUnsavedFileFlag(true);
294             this.$scope.save();
295         }
296
297         if (this.$scope.component.isResource() &&
298             (this.$scope.component as Resource).resourceType === ResourceType.VF ||
299                 (this.$scope.component as Resource).resourceType === ResourceType.PNF && (this.$scope.component as Resource).csarUUID) {
300             this.$scope.isShowOnboardingSelectionBrowse = true;
301             this.setImportedFileText();
302         } else {
303             this.$scope.isShowOnboardingSelectionBrowse = false;
304         }
305
306
307         //init file extensions based on the file that was imported.
308         if (this.$scope.component.isResource() && (<Resource>this.$scope.component).importedFile) {
309             let fileName:string = (<Resource>this.$scope.component).importedFile.filename;
310             let fileExtension:string = fileName.split(".").pop();
311             if (this.sdcConfig.csarFileExtension.indexOf(fileExtension.toLowerCase()) !== -1) {
312                 this.$scope.importedFileExtension = this.sdcConfig.csarFileExtension;
313                 (<Resource>this.$scope.component).importedFile.filetype = "csar";
314             } else if (this.sdcConfig.toscaFileExtension.indexOf(fileExtension.toLowerCase()) !== -1) {
315                 (<Resource>this.$scope.component).importedFile.filetype = "yaml";
316                 this.$scope.importedFileExtension = this.sdcConfig.toscaFileExtension;
317             }
318             this.$scope.restoreFile = angular.copy((<Resource>this.$scope.originComponent).importedFile); //create backup
319         } else if (this.$scope.isEditMode() && (<Resource>this.$scope.component).resourceType === ResourceType.VF) {
320             this.$scope.importedFileExtension = this.sdcConfig.csarFileExtension;
321             //(<Resource>this.$scope.component).importedFile.filetype="csar";
322         }
323
324
325
326         this.$scope.setValidState(true);
327
328         this.$scope.calculateUnique = (mainCategory:string, subCategory:string):string => {
329             let uniqueId:string = mainCategory;
330             if (subCategory) {
331                 uniqueId += "_#_" + subCategory; // Set the select category combobox to show the selected category.
332             }
333             return uniqueId;
334         };
335
336         //TODO remove this after handling contact in UI
337         if (this.$scope.isCreateMode()) {
338             this.$scope.component.contactId = this.cacheService.get("user").userId;
339             this.$scope.originComponent.contactId = this.$scope.component.contactId;
340         }
341
342
343         this.$scope.$on('$destroy', () => {
344             this.EventListenerService.unRegisterObserver(EVENTS.ON_LIFECYCLE_CHANGE_WITH_SAVE);
345             this.EventListenerService.unRegisterObserver(EVENTS.ON_LIFECYCLE_CHANGE);
346         });
347
348     };
349
350     // Convert category string MainCategory_#_SubCategory to Array with one item (like the server except)
351     private convertCategoryStringToOneArray = ():IMainCategory[] => {
352         let tmp = this.$scope.component.selectedCategory.split("_#_");
353         let mainCategory = tmp[0];
354         let subCategory = tmp[1];
355
356         // Find the selected category and add the relevant sub category.
357         let selectedMainCategory:IMainCategory = <IMainCategory>_.find(this.$scope.categories, function (item) {
358             return item["name"] === mainCategory;
359
360         });
361
362         let mainCategoryClone = angular.copy(selectedMainCategory);
363         if (subCategory) {
364             let selectedSubcategory = <ISubCategory>_.find(selectedMainCategory.subcategories, function (item) {
365                 return item["name"] === subCategory;
366             });
367             mainCategoryClone['subcategories'] = [angular.copy(selectedSubcategory)];
368         }
369         let tmpSelected = <IMainCategory> mainCategoryClone;
370
371         let result:IMainCategory[] = [];
372         result.push(tmpSelected);
373
374         return result;
375     };
376
377     private updateComponentNameInBreadcrumbs = ():void => {
378         // update breadcrum after changing name
379         this.$scope.breadcrumbsModel[1].updateSelectedMenuItemText(this.$scope.component.getComponentSubType() + ': ' + this.$scope.component.name);
380         this.$scope.updateMenuComponentName(this.$scope.component.name);
381     };
382
383     //Find if a category is applicable for External API or not
384     private isHiddenCategory = (category: string) => {
385         let items: Array<any> = new Array<any>();
386         items = this.$scope.sdcMenu.component_workspace_menu_option[this.$scope.component.getComponentSubType()];
387         for(let index = 0; index < items.length; ++index) {
388             if ((items[index].hiddenCategories && items[index].hiddenCategories.indexOf(category) > -1)) {
389                 return true;
390             }
391         }
392         return false;
393     };
394
395     private filteredCategories = () => {
396         let tempCategories: Array<IMainCategory> = new Array<IMainCategory>();
397         this.$scope.categories.forEach((category) => {
398             if (!this.isHiddenCategory(category.name)
399                 && this.$scope.isCreateMode()
400             ) {
401                 tempCategories.push(category);
402             } else if ((ComponentState.NOT_CERTIFIED_CHECKOUT === this.$scope.component.lifecycleState)
403                 && !this.isHiddenCategory(this.$scope.component.selectedCategory)
404                 && !this.isHiddenCategory(category.name)
405             ) {
406                 tempCategories.push(category);
407             } else if ((ComponentState.NOT_CERTIFIED_CHECKOUT === this.$scope.component.lifecycleState)
408                 && this.isHiddenCategory(this.$scope.component.selectedCategory)) {
409                 tempCategories.push(category);
410             }
411         });
412
413         return tempCategories;
414     };    
415    
416     private initScopeMethods = ():void => {
417
418         this.$scope.initCategoreis = ():void => {
419             if (this.$scope.componentType === ComponentType.RESOURCE) {
420                 this.$scope.categories = this.cacheService.get('resourceCategories');
421
422             }
423             if (this.$scope.componentType === ComponentType.SERVICE) {
424                 this.$scope.categories = this.cacheService.get('serviceCategories');
425
426                 //Remove categories from dropdown applicable for External API
427                 if (this.$scope.isCreateMode() || (ComponentState.NOT_CERTIFIED_CHECKOUT === this.$scope.component.lifecycleState)) {
428                     this.$scope.categories = this.filteredCategories();
429                     //Flag to disbale category if service is created through External API
430                     this.$scope.isHiddenCategorySelected = this.isHiddenCategory(this.$scope.component.selectedCategory);
431                 }
432                 
433             }
434         };
435
436         this.$scope.initInstantiationTypes = ():void => {
437             if (this.$scope.componentType === ComponentType.SERVICE) {
438                 this.$scope.instantiationTypes = new Array();
439                 this.$scope.instantiationTypes.push(instantiationType.A_LA_CARTE);
440                 this.$scope.instantiationTypes.push(instantiationType.MACRO);
441                 var instantiationTypeField:string =(<Service>this.$scope.component).instantiationType;
442                 if (instantiationTypeField === ""){
443                     this.$scope.instantiationTypes.push("");
444                 }
445                 else if (this.isCreateModeAvailable(instantiationTypeField)) {
446                     (<Service>this.$scope.component).instantiationType = instantiationType.A_LA_CARTE;
447
448                 }
449             }
450         };
451
452         this.$scope.initBaseTypes = ():void => {
453             if (this.$scope.componentType === ComponentType.SERVICE && this.$scope.component && this.$scope.component.categories) {
454                      let modelName = this.$scope.component.model ? this.$scope.component.model : null;
455                  this.elementService.getCategoryBasetypes(this.$scope.component.categories[0].name, modelName).subscribe((data: BaseTypeResponse[]) => {
456                          this.$scope.baseTypes = []
457                      this.$scope.baseTypeVersions = []
458                      data.forEach(baseType => {
459                              this.$scope.baseTypes.push(baseType.toscaResourceName)
460                          if (baseType.toscaResourceName === this.$scope.component.derivedFromGenericType){
461                                  baseType.versions.reverse().forEach(version => this.$scope.baseTypeVersions.push(version));
462                      }});
463                  })
464             }
465         };
466
467         this.$scope.initModel = ():void => {
468             this.$scope.models = new Array();
469             this.modelService.getModels().subscribe((modelsFound: Model[]) => {
470                 modelsFound.forEach(model => {this.$scope.models.push(model.name)});})
471             this.$scope.models.filter(model => model.name === this.$scope.component).model;
472         };
473
474         this.$scope.initEnvironmentContext = ():void => {
475             if (this.$scope.componentType === ComponentType.SERVICE) {
476                 this.$scope.environmentContextObj = this.cacheService.get('UIConfiguration').environmentContext;
477                 var environmentContext:string =(<Service>this.$scope.component).environmentContext;
478                 // In creation new service OR check outing old service without environmentContext parameter - set default value
479                 if(this.isCreateModeAvailable(environmentContext)){
480                     (<Service>this.$scope.component).environmentContext = this.$scope.environmentContextObj.defaultValue;
481                 }
482             }
483         };
484
485         this.$scope.validateField = (field:any):boolean => {
486             if (field && field.$dirty && field.$invalid) {
487                 return true;
488             }
489             return false;
490         };
491
492         this.$scope.openOnBoardingModal = ():void => {
493             if(this.$scope.component.vspArchived) return;
494             let csarUUID = (<Resource>this.$scope.component).csarUUID;
495             let csarVersion = (<Resource>this.$scope.component).csarVersion;
496             this.importVSPService.openOnboardingModal(csarUUID, csarVersion).subscribe((result) => {
497                 this.ComponentFactory.getComponentWithMetadataFromServer(result.type.toUpperCase(), result.previousComponent.uniqueId).then(
498                     (component:Component)=> {
499                     if (result.componentCsar && component.isResource()){
500                         this.cacheService.set(PREVIOUS_CSAR_COMPONENT, angular.copy(component));
501                         component = this.ComponentFactory.updateComponentFromCsar(result.componentCsar, <Resource>component);
502                     }
503                     this.$scope.setComponent(component);
504                     this.$scope.save();
505                     this.setImportedFileText();
506                 }, ()=> {
507                     // ERROR
508                 });
509             })
510         };
511
512         this.$scope.updateIcon = ():void => {
513             this.ModalsHandler.openUpdateIconModal(this.$scope.component).then((isDirty:boolean)=> {
514                 if(isDirty && !this.$scope.isCreateMode()){
515                     this.setUnsavedChanges(true);
516                 }
517             }, ()=> {
518                 // ERROR
519             });
520         };
521
522         this.$scope.possibleToUpdateIcon = ():boolean => {
523             if(this.$scope.componentCategories.selectedCategory && (!this.$scope.component.isResource() || this.$scope.component.vendorName) && !this.$scope.component.isAlreadyCertified()){
524                 return true;
525             }else{
526                 return false;
527             }
528         }
529
530         this.$scope.validateName = (isInit:boolean):void => {
531             if (isInit === undefined) {
532                 isInit = false;
533             }
534
535             let name = this.$scope.component.name;
536             if (!name || name === "") {
537                 if (this.$scope.editForm
538                     && this.$scope.editForm["componentName"]
539                     && this.$scope.editForm["componentName"].$error) {
540
541                     // Clear the error name already exists
542                     this.$scope.editForm["componentName"].$setValidity('nameExist', true);
543                 }
544
545                 return;
546             }
547             
548             let subtype:string = ComponentType.RESOURCE == this.$scope.componentType ? this.$scope.component.getComponentSubType() : undefined;
549             if (subtype == "SRVC") {
550                 subtype = "VF"
551             }
552
553             const onFailed = (response) => {
554                 // console.info('onFaild', response);
555                 // this.$scope.isLoading = false;
556             };
557
558             const onSuccess = (validation:IValidate) => {
559                 this.$scope.editForm['componentName'].$setValidity('nameExist', validation.isValid);
560                 if (validation.isValid) {
561                     // update breadcrumb after changing name
562                     this.updateComponentNameInBreadcrumbs();
563                 }
564             };
565
566             if (isInit) {
567                 // When page is init after update
568                 if (this.$scope.component.name !== this.$scope.originComponent.name) {
569                     if (!(this.$scope.componentType === ComponentType.RESOURCE && (<Resource>this.$scope.component).csarUUID !== undefined)
570                     ) {
571                         this.$scope.component.validateName(name, subtype).then(onSuccess, onFailed);
572                     }
573                 }
574             } else {
575                 // Validating on change (has debounce)
576                 if (this.$scope.editForm
577                     && this.$scope.editForm["componentName"]
578                     && this.$scope.editForm["componentName"].$error
579                     && !this.$scope.editForm["componentName"].$error.pattern
580                     && (!this.$scope.originComponent.name || this.$scope.component.name.toUpperCase() !== this.$scope.originComponent.name.toUpperCase())
581                 ) {
582                     if (!(this.$scope.componentType === ComponentType.RESOURCE && (this.$scope.component as Resource).csarUUID !== undefined)
583                     ) {
584                         this.$scope.component.validateName(name, subtype).then(onSuccess, onFailed);
585                     }
586                 } else if (this.$scope.editForm && this.$scope.originComponent.name && this.$scope.component.name.toUpperCase() === this.$scope.originComponent.name.toUpperCase()) {
587                     // Clear the error
588                     this.$scope.editForm['componentName'].$setValidity('nameExist', true);
589                 }
590             }
591         };
592
593
594         this.EventListenerService.registerObserverCallback(EVENTS.ON_LIFECYCLE_CHANGE_WITH_SAVE, (nextState) => {
595             if (this.$state.current.data.unsavedChanges && this.$scope.isValidForm) {
596                 this.$scope.save().then(() => {
597                     this.$scope.handleChangeLifecycleState(nextState);
598                 }, () => {
599                     console.error('Save failed, unable to change lifecycle state to ' + nextState);
600                 });
601             } else if(!this.$scope.isValidForm){
602                 console.error('Form is not valid');
603             } else {
604                 let newCsarVersion:string;
605                 if(this.$scope.unsavedFile) {
606                     newCsarVersion = (this.$scope.component as Resource).csarVersion;
607                 }
608                 if(this.$stateParams.componentCsar && !this.$scope.isCreateMode()) {
609                     const onError = (): void => {
610                         if (this.$scope.component.lifecycleState === 'NOT_CERTIFIED_CHECKIN') {
611                             this.$scope.revert();
612                         }
613                     };
614                     this.$scope.handleChangeLifecycleState(nextState, newCsarVersion, onError);
615
616                 } else {
617                     this.$scope.handleChangeLifecycleState(nextState, newCsarVersion);
618                 }
619             }
620         });
621
622         this.$scope.revert = ():void => {
623             // in state of import file leave the file in place
624
625             this.$scope.setComponent(this.ComponentFactory.createComponent(this.$scope.originComponent));
626
627             if (this.$scope.component.isResource() && this.$scope.restoreFile) {
628                 (this.$scope.component as Resource).importedFile = angular.copy(this.$scope.restoreFile);
629             }
630
631             this.setImportedFileText();
632             this.$scope.updateBreadcrumbs(this.$scope.component); // update on workspace
633
634             this.$scope.componentCategories.selectedCategory = this.$scope.originComponent.selectedCategory;
635             this.setUnsavedChanges(false);
636             this.$scope.updateUnsavedFileFlag(false);
637             this.$scope.editForm.$setPristine();
638         };
639
640         this.$scope.onImportFileChange = () => {
641
642             if( !this.$scope.restoreFile && this.$scope.editForm.fileElement.value && this.$scope.editForm.fileElement.value.filename || // if file started empty but we have added a new one
643                 this.$scope.restoreFile && !angular.equals(this.$scope.restoreFile, this.$scope.editForm.fileElement.value)){ // or file was swapped for a new one
644                 this.$scope.updateUnsavedFileFlag(true);
645             } else {
646                 this.$scope.updateUnsavedFileFlag(false);
647                 this.$scope.editForm.fileElement.$setPristine();
648             }
649         };
650
651         this.$scope.$watchCollection('component.name', (newData: any): void => {
652             this.$scope.validateName(false);
653         });
654
655         // Notify the parent if this step valid or not.
656         this.$scope.$watch('editForm.$valid', (newVal, oldVal) => {
657             this.$scope.setValidState(newVal);
658         });
659
660         this.$scope.$watch('editForm.$dirty', (newVal, oldVal) => {
661             if (newVal && !this.$scope.isCreateMode()) {
662                 this.setUnsavedChanges(true);
663             }
664
665         });
666
667         this.$scope.onCategoryChange = (): void => {
668             this.$scope.component.selectedCategory = this.$scope.componentCategories.selectedCategory;
669             this.$scope.component.categories = this.convertCategoryStringToOneArray();
670             this.$scope.component.icon = DEFAULT_ICON;
671             if (this.$scope.component.categories[0].metadataKeys) {
672                 for (let metadataKey of this.$scope.component.categories[0].metadataKeys) {
673                     if (!this.$scope.component.categorySpecificMetadata[metadataKey.name]) {
674                         this.$scope.component.categorySpecificMetadata[metadataKey.name] = metadataKey.defaultValue ? metadataKey.defaultValue : "";
675                    }
676                 }
677             }
678             if (this.$scope.component.categories[0].subcategories && this.$scope.component.categories[0].subcategories[0].metadataKeys) {
679                 for (let metadataKey of this.$scope.component.categories[0].subcategories[0].metadataKeys) {
680                     if (!this.$scope.component.categorySpecificMetadata[metadataKey.name]) {
681                         this.$scope.component.categorySpecificMetadata[metadataKey.name] = metadataKey.defaultValue ? metadataKey.defaultValue : "";
682                    }
683                 }
684             }
685             if (this.$scope.componentType === ComponentType.SERVICE && this.$scope.component.categories[0]) {
686                     let modelName : string = this.$scope.component.model ? this.$scope.component.model : null;
687                     this.elementService.getCategoryBasetypes(this.$scope.component.categories[0].name, modelName).subscribe((data: BaseTypeResponse[]) => {
688                 
689                     if(this.$scope.isCreateMode()){
690                         this.$scope.baseTypes = []
691                         this.$scope.baseTypeVersions = []
692                         data.forEach(baseType => this.$scope.baseTypes.push(baseType.toscaResourceName));
693                         data[0].versions.reverse().forEach(version => this.$scope.baseTypeVersions.push(version));
694                         this.$scope.component.derivedFromGenericType = data[0].toscaResourceName;
695                         this.$scope.component.derivedFromGenericVersion = data[0].versions[0];
696                     } else {
697                         var isValidForBaseType:boolean = false;
698                         data.forEach(baseType => {if (!this.$scope.component.derivedFromGenericType || baseType.toscaResourceName === this.$scope.component.derivedFromGenericType){
699                             isValidForBaseType = true;
700                         };});
701                         this.$scope.editForm['category'].$setValidity('validForBaseType', isValidForBaseType);
702                     }
703                 });
704             }   
705         };
706
707         this.$scope.onEcompGeneratedNamingChange = (): void => {
708             if (!(this.$scope.component as Service).ecompGeneratedNaming) {
709                 (this.$scope.component as Service).namingPolicy = '';
710             }
711         };
712
713         this.$scope.onBaseTypeChange = (): void => {
714                 let modelName : string = this.$scope.component.model ? this.$scope.component.model : null;
715             this.elementService.getCategoryBasetypes(this.$scope.component.categories[0].name, modelName).subscribe((data: BaseTypeResponse[]) => {
716                      this.$scope.baseTypeVersions = []
717                      data.forEach(baseType => {
718                              if(baseType.toscaResourceName === this.$scope.component.derivedFromGenericType) {
719                                      baseType.versions.reverse().forEach(version => this.$scope.baseTypeVersions.push(version));
720                              this.$scope.component.derivedFromGenericVersion = baseType.versions[0];
721                              };
722                      });
723              })
724         };
725
726         this.$scope.onModelChange = (): void => {
727             if (this.$scope.componentType === ComponentType.SERVICE && this.$scope.component && this.$scope.component.categories) {
728                      let modelName = this.$scope.component.model ? this.$scope.component.model : null;
729                  this.elementService.getCategoryBasetypes(this.$scope.component.categories[0].name, modelName).subscribe((data: BaseTypeResponse[]) => {
730                                 this.$scope.baseTypes = []
731                         this.$scope.baseTypeVersions = []
732                         data.forEach(baseType => this.$scope.baseTypes.push(baseType.toscaResourceName));
733                         data[0].versions.reverse().forEach(version => this.$scope.baseTypeVersions.push(version));
734                         this.$scope.component.derivedFromGenericType = data[0].toscaResourceName;
735                         this.$scope.component.derivedFromGenericVersion = data[0].versions[0];
736                  })
737             }
738         };
739
740         this.$scope.onVendorNameChange = (oldVendorName: string): void => {
741             if (this.$scope.component.icon === oldVendorName) {
742                 this.$scope.component.icon = DEFAULT_ICON;
743             }
744         };
745         this.EventListenerService.registerObserverCallback(EVENTS.ON_LIFECYCLE_CHANGE, this.$scope.reload);
746
747
748         this.$scope.isMetadataKeyMandatory = (key: string): boolean => {
749             let metadataKey = this.getMetadataKey(this.$scope.component.categories, key);
750             return metadataKey && metadataKey.mandatory;
751         }
752
753         this.$scope.getMetadataKeyValidValues = (key: string): string[] => {
754             let metadataKey = this.getMetadataKey(this.$scope.component.categories, key);
755             if (metadataKey) {
756                 return metadataKey.validValues;
757             }
758             return [];  
759         }
760
761         this.$scope.isMetadataKeyForComponentCategory = (key: string): boolean => {
762             return this.getMetadataKey(this.$scope.component.categories, key) != null;
763         }
764
765         this.$scope.isCategoryServiceMetadataKey = (key: string): boolean => {
766             return this.isServiceMetadataKey(key);
767         }
768
769         this.$scope.isMetadataKeyForComponentCategoryService = (key: string, attribute: string): boolean => {
770             let metadatakey = this.getMetadataKey(this.$scope.component.categories, key);
771             if (metadatakey && (!this.$scope.component[attribute] || !metadatakey.validValues.find(v => v === this.$scope.component[attribute]))) {
772                 this.$scope.component[attribute] = metadatakey.defaultValue;
773             }
774             return metadatakey != null;
775          }
776     }
777
778     private setUnsavedChanges = (hasChanges: boolean): void => {
779         this.$state.current.data.unsavedChanges = hasChanges;
780     }
781
782     private getMetadataKey(categories: IMainCategory[], key: string) : IMetadataKey {
783         let metadataKey = this.getSubcategoryMetadataKey(this.$scope.component.categories, key);
784         if (!metadataKey){
785             return this.getCategoryMetadataKey(this.$scope.component.categories, key);
786         }
787         return metadataKey;
788     }
789
790     private getSubcategoryMetadataKey(categories: IMainCategory[], key: string) : IMetadataKey {
791             if (categories[0].subcategories && categories[0].subcategories[0].metadataKeys && categories[0].subcategories[0].metadataKeys.some(metadataKey => metadataKey.name == key)) {
792             return categories[0].subcategories[0].metadataKeys.find(metadataKey => metadataKey.name == key);
793         }
794         return null;
795     }
796
797     private getCategoryMetadataKey(categories: IMainCategory[], key: string) : IMetadataKey {
798             if (categories[0].metadataKeys && categories[0].metadataKeys.some(metadataKey => metadataKey.name == key)) {
799             return categories[0].metadataKeys.find(metadataKey => metadataKey.name == key);
800         }
801         return null;
802     }
803
804     private isServiceMetadataKey(key: string) : boolean {
805         return CATEGORY_SERVICE_METADATA_KEYS.indexOf(key) > -1;
806     }
807
808 }
809