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