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