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