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