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