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