Enable selection of base type of service
[sdc.git] / catalog-ui / src / app / view-models / workspace / tabs / general / general-view-model.ts
index c60a490..2876544 100644 (file)
@@ -7,9 +7,9 @@
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
- * 
+ *
  *      http://www.apache.org/licenses/LICENSE-2.0
- * 
+ *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  */
 
 'use strict';
+import * as _ from "lodash";
 import {ModalsHandler, ValidationUtils, EVENTS, CHANGE_COMPONENT_CSAR_VERSION_FLAG, ComponentType, DEFAULT_ICON,
-    ResourceType, ComponentState} from "app/utils";
-import {CacheService, EventListenerService, ProgressService, OnboardingService} from "app/services";
-import {IAppConfigurtaion, IValidate, IMainCategory, Resource, ISubCategory,Service, ICsarComponent} from "app/models";
+    ResourceType, ComponentState, instantiationType, ComponentFactory} from "app/utils";
+import { EventListenerService, ProgressService} from "app/services";
+import {CacheService, OnboardingService, ImportVSPService, ElementService} from "app/services-ng2";
+import {IAppConfigurtaion, IValidate, IMainCategory, Resource, ISubCategory,Service, ICsarComponent, Component, IMetadataKey} from "app/models";
 import {IWorkspaceViewModelScope} from "app/view-models/workspace/workspace-view-model";
 import {Dictionary} from "lodash";
+import { PREVIOUS_CSAR_COMPONENT, CATEGORY_SERVICE_METADATA_KEYS } from "../../../../utils/constants";
+import { Observable, Subject } from "rxjs";
+import { MetadataEntry } from "app/models/metadataEntry";
+import { Metadata } from "app/models/metadata";
 
 export class Validation {
     componentNameValidationPattern:RegExp;
@@ -34,18 +40,22 @@ export class Validation {
     VendorNameValidationPattern:RegExp;
     VendorModelNumberValidationPattern:RegExp;
     commentValidationPattern:RegExp;
-    projectCodeValidationPattern:RegExp;
 }
 
 export class componentCategories {//categories field bind to this obj in order to solve this bug: DE242059
     selectedCategory:string;
 }
 
+export interface IEnvironmentContext {
+    defaultValue:string;
+    validValues:Array<string>;
+}
 
 export interface IGeneralScope extends IWorkspaceViewModelScope {
     validation:Validation;
     editForm:ng.IFormController;
     categories:Array<IMainCategory>;
+    environmentContextObj:IEnvironmentContext;
     latestCategoryId:string;
     latestVendorName:string;
     importedFileExtension:any;
@@ -53,11 +63,15 @@ export interface IGeneralScope extends IWorkspaceViewModelScope {
     isShowFileBrowse:boolean;
     isShowOnboardingSelectionBrowse:boolean;
     importedToscaBrowseFileText:string;
-    importCsarProgressKey:string;
+    importCsarProProgressKey:string;
     browseFileLabel:string;
     componentCategories:componentCategories;
+    instantiationTypes:Array<instantiationType>;
+    isHiddenCategorySelected: boolean;
 
-    onToscaFileChange():void;
+    save():Promise<any>;
+    revert():void;
+    onImportFileChange():void;
     validateField(field:any):boolean;
     validateName(isInit:boolean):void;
     calculateUnique(mainCategory:string, subCategory:string):string; // Build unique string from main and sub category
@@ -65,12 +79,18 @@ export interface IGeneralScope extends IWorkspaceViewModelScope {
     convertCategoryStringToOneArray(category:string, subcategory:string):Array<IMainCategory>;
     onCategoryChange():void;
     onEcompGeneratedNamingChange():void;
+    onBaseTypeChange():void;
     openOnBoardingModal():void;
     initCategoreis():void;
+    initEnvironmentContext():void;
+    initInstantiationTypes():void;
+    initBaseTypes():void;
+    onInstantiationTypeChange():void;
     updateIcon():void;
     possibleToUpdateIcon():boolean;
 }
 
+// tslint:disable-next-line:max-classes-per-file
 export class GeneralViewModel {
 
     static '$inject' = [
@@ -85,7 +105,6 @@ export class GeneralViewModel {
         'CommentValidationPattern',
         'ValidationUtils',
         'sdcConfig',
-        'ProjectCodeValidationPattern',
         '$state',
         'ModalsHandler',
         'EventListenerService',
@@ -94,7 +113,11 @@ export class GeneralViewModel {
         '$interval',
         '$filter',
         '$timeout',
-        'Sdc.Services.OnboardingService'
+        'OnboardingService',
+        'ComponentFactory',
+        'ImportVSPService',
+        'ElementService',
+        '$stateParams'
     ];
 
     constructor(private $scope:IGeneralScope,
@@ -108,7 +131,6 @@ export class GeneralViewModel {
                 private CommentValidationPattern:RegExp,
                 private ValidationUtils:ValidationUtils,
                 private sdcConfig:IAppConfigurtaion,
-                private ProjectCodeValidationPattern:RegExp,
                 private $state:ng.ui.IStateService,
                 private ModalsHandler:ModalsHandler,
                 private EventListenerService:EventListenerService,
@@ -117,7 +139,11 @@ export class GeneralViewModel {
                 protected $interval:any,
                 private $filter:ng.IFilterService,
                 private $timeout:ng.ITimeoutService,
-                private onBoardingService:OnboardingService) {
+                private onBoardingService: OnboardingService,
+                private ComponentFactory:ComponentFactory,
+                private importVSPService: ImportVSPService,
+                private elementService: ElementService,
+                private $stateParams: any) {
 
         this.initScopeValidation();
         this.initScopeMethods();
@@ -136,65 +162,83 @@ export class GeneralViewModel {
         this.$scope.validation.VendorNameValidationPattern = this.VendorNameValidationPattern;
         this.$scope.validation.VendorModelNumberValidationPattern = this.VendorModelNumberValidationPattern;
         this.$scope.validation.commentValidationPattern = this.CommentValidationPattern;
-        this.$scope.validation.projectCodeValidationPattern = this.ProjectCodeValidationPattern;
     };
 
-    private initImportedToscaBrowseFile = ():void =>{
-        // Init the decision if to show onboarding
-        this.$scope.isShowOnboardingSelectionBrowse = false;
-        if (this.$scope.component.isResource() &&
-            this.$scope.isEditMode() &&
-            (<Resource>this.$scope.component).resourceType == ResourceType.VF &&
-            (<Resource>this.$scope.component).csarUUID) {
-            this.$scope.isShowOnboardingSelectionBrowse = true;
-            let onboardCsarFilesMap:Dictionary<Dictionary<string>> = this.cacheService.get('onboardCsarFilesMap');
-            // The onboardCsarFilesMap in cache contains map of [packageId]:[vsp display name for brows]
-            // if the map is empty - Do request to BE
-            if(onboardCsarFilesMap) {
-                if (onboardCsarFilesMap[(<Resource>this.$scope.component).csarUUID]){
-                    this.$scope.importedToscaBrowseFileText = onboardCsarFilesMap[(<Resource>this.$scope.component).csarUUID][(<Resource>this.$scope.component).csarVersion];
+    private loadOnboardingFileCache = (): Observable<Dictionary<Dictionary<string>>> => {
+        let onboardCsarFilesMap:Dictionary<Dictionary<string>>;
+        let onSuccess = (vsps:Array<ICsarComponent>) => {
+            onboardCsarFilesMap = {};
+            _.each(vsps, (vsp:ICsarComponent)=>{
+                onboardCsarFilesMap[vsp.packageId] = onboardCsarFilesMap[vsp.packageId] || {};
+                onboardCsarFilesMap[vsp.packageId][vsp.version] = vsp.vspName + " (" + vsp.version + ")";
+            });
+            this.cacheService.set('onboardCsarFilesMap', onboardCsarFilesMap);
+            return onboardCsarFilesMap;
+        };
+        let onError = (): void =>{
+            console.log("Error getting onboarding list");
+        };
+        return this.onBoardingService.getOnboardingVSPs().map(onSuccess, onError);
+    };
+
+    private setImportedFileText = ():void => {
+
+        if(!this.$scope.isShowOnboardingSelectionBrowse) return;
+
+        //these variables makes it easier to read this logic
+        let csarUUID:string = (<Resource>this.$scope.component).csarUUID;
+        let csarVersion:string = (<Resource>this.$scope.component).csarVersion;
+
+        let onboardCsarFilesMap:Dictionary<Dictionary<string>> = this.cacheService.get('onboardCsarFilesMap');
+        let assignFileName = ():void => {
+            if(this.$scope.component.vspArchived){
+                this.$scope.importedToscaBrowseFileText = 'VSP is archived';
+            } else {
+                if(this.$stateParams.componentCsar && this.$scope.component.lifecycleState === 'NOT_CERTIFIED_CHECKIN' && !this.$scope.isCreateMode()) {
+                    this.$scope.importedToscaBrowseFileText = this.$scope.originComponent.name + ' (' + (this.$scope.originComponent as Resource).csarVersion + ')';
+                } else {
+                    this.$scope.importedToscaBrowseFileText = onboardCsarFilesMap[csarUUID][csarVersion];
                 }
             }
-            if(!onboardCsarFilesMap || !this.$scope.importedToscaBrowseFileText){
-
-                let onSuccess = (vsps:Array<ICsarComponent>): void =>{
-                    onboardCsarFilesMap = {};
-                    _.each(vsps, (vsp:ICsarComponent)=>{
-                        onboardCsarFilesMap[vsp.packageId] = onboardCsarFilesMap[vsp.packageId] || {};
-                        onboardCsarFilesMap[vsp.packageId][vsp.version] = vsp.vspName + " (" + vsp.version + ")";
-                    });
-                    this.cacheService.set('onboardCsarFilesMap', onboardCsarFilesMap);
-                    this.$scope.importedToscaBrowseFileText = onboardCsarFilesMap[(<Resource>this.$scope.component).csarUUID][(<Resource>this.$scope.component).csarVersion];
-                };
-
-                let onError = (): void =>{
-                    console.log("Error getting onboarding list");
-                };
-
-                this.onBoardingService.getOnboardingVSPs().then(onSuccess, onError);
-            }
         }
-    };
 
-    private initScope = ():void => {
 
-        // Work around to change the csar version
-        if (this.cacheService.get(CHANGE_COMPONENT_CSAR_VERSION_FLAG)) {
-            (<Resource>this.$scope.component).csarVersion = this.cacheService.get(CHANGE_COMPONENT_CSAR_VERSION_FLAG);
+        if(this.$scope.component.vspArchived || (onboardCsarFilesMap && onboardCsarFilesMap[csarUUID] && onboardCsarFilesMap[csarUUID][csarVersion])){ //check that the file name is already in cache
+            assignFileName();
+        } else {
+            this.loadOnboardingFileCache().subscribe((onboardingFiles) => {
+                onboardCsarFilesMap = onboardingFiles;
+                this.cacheService.set('onboardCsarFilesMap', onboardingFiles);
+                assignFileName();
+            }, ()=> {});
         }
 
+    }
+
+    isCreateModeAvailable(verifyObj:string): boolean {
+        var isCheckout:boolean = ComponentState.NOT_CERTIFIED_CHECKOUT === this.$scope.component.lifecycleState;
+        return this.$scope.isCreateMode() || (isCheckout && !verifyObj)
+    }
+
+    private initScope = ():void => {
+
         this.$scope.importCsarProgressKey = "importCsarProgressKey";
-        this.$scope.browseFileLabel = this.$scope.component.isResource() && (<Resource>this.$scope.component).resourceType === ResourceType.VF ? "Upload file" : "Upload VFC";
+
+        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:';
         this.$scope.progressService = this.progressService;
         this.$scope.componentCategories = new componentCategories();
         this.$scope.componentCategories.selectedCategory = this.$scope.component.selectedCategory;
 
+
         // Init UIModel
         this.$scope.component.tags = _.without(this.$scope.component.tags, this.$scope.component.name);
 
         // Init categories
         this.$scope.initCategoreis();
 
+        // Init Environment Context
+        this.$scope.initEnvironmentContext();
+
         // Init the decision if to show file browse.
         this.$scope.isShowFileBrowse = false;
         if (this.$scope.component.isResource()) {
@@ -203,12 +247,53 @@ export class GeneralViewModel {
             if (resource.importedFile) { // Component has imported file.
                 this.$scope.isShowFileBrowse = true;
             }
-            if (this.$scope.isEditMode() && resource.resourceType == ResourceType.VF && !resource.csarUUID) {
+            if (resource.resourceType === ResourceType.VF && !resource.csarUUID) {
+                this.$scope.isShowFileBrowse = true;
+            }
+        } else if(this.$scope.component.isService()){
+            let service: Service = <Service>this.$scope.component;
+            console.log(service.name + ": " + service.csarUUID);
+            if (service.importedFile) { // Component has imported file.
+                this.$scope.isShowFileBrowse = true;
+                (<Service>this.$scope.component).serviceType = 'Service';
+            }
+            if (this.$scope.isEditMode() && service.serviceType == 'Service' && !service.csarUUID) {
                 this.$scope.isShowFileBrowse = true;
             }
+            // Init Instantiation types
+            this.$scope.initInstantiationTypes();
+            this.$scope.initBaseTypes();
+        }
+
+        if (this.cacheService.get(PREVIOUS_CSAR_COMPONENT)) { //keep the old component in the cache until checkout, so we dont need to pass it around
+            this.$scope.setOriginComponent(this.cacheService.get(PREVIOUS_CSAR_COMPONENT));
+            this.cacheService.remove(PREVIOUS_CSAR_COMPONENT);
+        }
+
+        if (this.$stateParams.componentCsar && !this.$scope.isCreateMode()) {
+            this.$scope.updateUnsavedFileFlag(true);
+            // We are coming from update VSP modal we need to automatically checkout (if needed) and save the VF
+            if (this.$scope.component.lifecycleState !== ComponentState.NOT_CERTIFIED_CHECKOUT) {
+                // Checkout is needed after that a save will be invoked in workspace-view.handleLifeCycleStateChange
+                this.EventListenerService.notifyObservers(EVENTS.ON_LIFECYCLE_CHANGE_WITH_SAVE, 'checkOut');
+                // if(this.$scope.component.lifecycleState !== 'NOT_CERTIFIED_CHECKIN') {
+                //     (<Resource>this.$scope.component).csarVersion = this.$stateParams.componentCsar.csarVersion;
+                // }
+            } else {
+                this.$scope.save();
+            }
+        }
+
+
+        if (this.$scope.component.isResource() &&
+            (this.$scope.component as Resource).resourceType === ResourceType.VF ||
+                (this.$scope.component as Resource).resourceType === ResourceType.PNF && (this.$scope.component as Resource).csarUUID) {
+            this.$scope.isShowOnboardingSelectionBrowse = true;
+            this.setImportedFileText();
+        } else {
+            this.$scope.isShowOnboardingSelectionBrowse = false;
         }
 
-        this.initImportedToscaBrowseFile();
 
         //init file extensions based on the file that was imported.
         if (this.$scope.component.isResource() && (<Resource>this.$scope.component).importedFile) {
@@ -221,11 +306,14 @@ export class GeneralViewModel {
                 (<Resource>this.$scope.component).importedFile.filetype = "yaml";
                 this.$scope.importedFileExtension = this.sdcConfig.toscaFileExtension;
             }
+            this.$scope.restoreFile = angular.copy((<Resource>this.$scope.originComponent).importedFile); //create backup
         } else if (this.$scope.isEditMode() && (<Resource>this.$scope.component).resourceType === ResourceType.VF) {
             this.$scope.importedFileExtension = this.sdcConfig.csarFileExtension;
             //(<Resource>this.$scope.component).importedFile.filetype="csar";
         }
 
+
+
         this.$scope.setValidState(true);
 
         this.$scope.calculateUnique = (mainCategory:string, subCategory:string):string => {
@@ -239,12 +327,19 @@ export class GeneralViewModel {
         //TODO remove this after handling contact in UI
         if (this.$scope.isCreateMode()) {
             this.$scope.component.contactId = this.cacheService.get("user").userId;
+            this.$scope.originComponent.contactId = this.$scope.component.contactId;
         }
 
+
+        this.$scope.$on('$destroy', () => {
+            this.EventListenerService.unRegisterObserver(EVENTS.ON_LIFECYCLE_CHANGE_WITH_SAVE);
+            this.EventListenerService.unRegisterObserver(EVENTS.ON_LIFECYCLE_CHANGE);
+        });
+
     };
 
     // Convert category string MainCategory_#_SubCategory to Array with one item (like the server except)
-    private convertCategoryStringToOneArray = ():Array<IMainCategory> => {
+    private convertCategoryStringToOneArray = ():IMainCategory[] => {
         let tmp = this.$scope.component.selectedCategory.split("_#_");
         let mainCategory = tmp[0];
         let subCategory = tmp[1];
@@ -264,18 +359,51 @@ export class GeneralViewModel {
         }
         let tmpSelected = <IMainCategory> mainCategoryClone;
 
-        let result:Array<IMainCategory> = [];
+        let result:IMainCategory[] = [];
         result.push(tmpSelected);
 
         return result;
     };
 
     private updateComponentNameInBreadcrumbs = ():void => {
-        //update breadcrum after changing name
+        // update breadcrum after changing name
         this.$scope.breadcrumbsModel[1].updateSelectedMenuItemText(this.$scope.component.getComponentSubType() + ': ' + this.$scope.component.name);
         this.$scope.updateMenuComponentName(this.$scope.component.name);
     };
 
+    //Find if a category is applicable for External API or not
+    private isHiddenCategory = (category: string) => {
+        let items: Array<any> = new Array<any>();
+        items = this.$scope.sdcMenu.component_workspace_menu_option[this.$scope.component.getComponentSubType()];
+        for(let index = 0; index < items.length; ++index) {
+            if ((items[index].hiddenCategories && items[index].hiddenCategories.indexOf(category) > -1)) {
+                return true;
+            }
+        }
+        return false;
+    };
+
+    private filteredCategories = () => {
+        let tempCategories: Array<IMainCategory> = new Array<IMainCategory>();
+        this.$scope.categories.forEach((category) => {
+            if (!this.isHiddenCategory(category.name)
+                && this.$scope.isCreateMode()
+            ) {
+                tempCategories.push(category);
+            } else if ((ComponentState.NOT_CERTIFIED_CHECKOUT === this.$scope.component.lifecycleState)
+                && !this.isHiddenCategory(this.$scope.component.selectedCategory)
+                && !this.isHiddenCategory(category.name)
+            ) {
+                tempCategories.push(category);
+            } else if ((ComponentState.NOT_CERTIFIED_CHECKOUT === this.$scope.component.lifecycleState)
+                && this.isHiddenCategory(this.$scope.component.selectedCategory)) {
+                tempCategories.push(category);
+            }
+        });
+
+        return tempCategories;
+    };    
+   
     private initScopeMethods = ():void => {
 
         this.$scope.initCategoreis = ():void => {
@@ -285,6 +413,55 @@ export class GeneralViewModel {
             }
             if (this.$scope.componentType === ComponentType.SERVICE) {
                 this.$scope.categories = this.cacheService.get('serviceCategories');
+
+                //Remove categories from dropdown applicable for External API
+                if (this.$scope.isCreateMode() || (ComponentState.NOT_CERTIFIED_CHECKOUT === this.$scope.component.lifecycleState)) {
+                    this.$scope.categories = this.filteredCategories();
+                    //Flag to disbale category if service is created through External API
+                    this.$scope.isHiddenCategorySelected = this.isHiddenCategory(this.$scope.component.selectedCategory);
+                }
+                
+            }
+        };
+
+        this.$scope.initInstantiationTypes = ():void => {
+            if (this.$scope.componentType === ComponentType.SERVICE) {
+                this.$scope.instantiationTypes = new Array();
+                this.$scope.instantiationTypes.push(instantiationType.A_LA_CARTE);
+                this.$scope.instantiationTypes.push(instantiationType.MACRO);
+                var instantiationTypeField:string =(<Service>this.$scope.component).instantiationType;
+                if (instantiationTypeField === ""){
+                    this.$scope.instantiationTypes.push("");
+                }
+                else if (this.isCreateModeAvailable(instantiationTypeField)) {
+                    (<Service>this.$scope.component).instantiationType = instantiationType.A_LA_CARTE;
+
+                }
+            }
+        };
+
+        this.$scope.initBaseTypes = ():void => {
+            if (this.$scope.componentType === ComponentType.SERVICE && this.$scope.component && this.$scope.component.categories) {
+                 this.elementService.getCategoryBasetypes(this.$scope.component.categories[0].name).subscribe((data: BaseTypeResponse[]) => {
+                        this.$scope.baseTypes = []
+                     this.$scope.baseTypeVersions = []
+                     data.forEach(baseType => {
+                            this.$scope.baseTypes.push(baseType.toscaResourceName)
+                         if (baseType.toscaResourceName === this.$scope.component.derivedFromGenericType){
+                                baseType.versions.reverse().forEach(version => this.$scope.baseTypeVersions.push(version));
+                     }});
+                 })
+            }
+        };
+
+        this.$scope.initEnvironmentContext = ():void => {
+            if (this.$scope.componentType === ComponentType.SERVICE) {
+                this.$scope.environmentContextObj = this.cacheService.get('UIConfiguration').environmentContext;
+                var environmentContext:string =(<Service>this.$scope.component).environmentContext;
+                // In creation new service OR check outing old service without environmentContext parameter - set default value
+                if(this.isCreateModeAvailable(environmentContext)){
+                    (<Service>this.$scope.component).environmentContext = this.$scope.environmentContextObj.defaultValue;
+                }
             }
         };
 
@@ -296,19 +473,29 @@ export class GeneralViewModel {
         };
 
         this.$scope.openOnBoardingModal = ():void => {
+            if(this.$scope.component.vspArchived) return;
             let csarUUID = (<Resource>this.$scope.component).csarUUID;
-            this.ModalsHandler.openOnboadrdingModal('Update', csarUUID).then(()=> {
-                // OK
-                this.$scope.uploadFileChangedInGeneralTab();
-            }, ()=> {
-                // ERROR
-            });
+            let csarVersion = (<Resource>this.$scope.component).csarVersion;
+            this.importVSPService.openOnboardingModal(csarUUID, csarVersion).subscribe((result) => {
+                this.ComponentFactory.getComponentWithMetadataFromServer(result.type.toUpperCase(), result.previousComponent.uniqueId).then(
+                    (component:Component)=> {
+                    if (result.componentCsar && component.isResource()){
+                        this.cacheService.set(PREVIOUS_CSAR_COMPONENT, angular.copy(component));
+                        component = this.ComponentFactory.updateComponentFromCsar(result.componentCsar, <Resource>component);
+                    }
+                    this.$scope.setComponent(component);
+                    this.$scope.save();
+                    this.setImportedFileText();
+                }, ()=> {
+                    // ERROR
+                });
+            })
         };
 
         this.$scope.updateIcon = ():void => {
             this.ModalsHandler.openUpdateIconModal(this.$scope.component).then((isDirty:boolean)=> {
-                if(!this.$scope.isCreateMode()){
-                    this.$state.current.data.unsavedChanges = this.$state.current.data.unsavedChanges || isDirty;
+                if(isDirty && !this.$scope.isCreateMode()){
+                    this.setUnsavedChanges(true);
                 }
             }, ()=> {
                 // ERROR
@@ -316,7 +503,7 @@ export class GeneralViewModel {
         };
 
         this.$scope.possibleToUpdateIcon = ():boolean => {
-            if(this.$scope.componentCategories.selectedCategory && (!this.$scope.component.isResource() || this.$scope.component.vendorName)){
+            if(this.$scope.componentCategories.selectedCategory && (!this.$scope.component.isResource() || this.$scope.component.vendorName) && !this.$scope.component.isAlreadyCertified()){
                 return true;
             }else{
                 return false;
@@ -340,18 +527,21 @@ export class GeneralViewModel {
 
                 return;
             }
-            //?????????????????????????
+           
             let subtype:string = ComponentType.RESOURCE == this.$scope.componentType ? this.$scope.component.getComponentSubType() : undefined;
+            if (subtype == "SRVC") {
+                subtype = "VF"
+            }
 
-            let onFailed = (response) => {
-                //console.info('onFaild', response);
-                //this.$scope.isLoading = false;
+            const onFailed = (response) => {
+                // console.info('onFaild', response);
+                // this.$scope.isLoading = false;
             };
 
-            let onSuccess = (validation:IValidate) => {
-                this.$scope.editForm["componentName"].$setValidity('nameExist', validation.isValid);
+            const onSuccess = (validation:IValidate) => {
+                this.$scope.editForm['componentName'].$setValidity('nameExist', validation.isValid);
                 if (validation.isValid) {
-                    //update breadcrumb after changing name
+                    // update breadcrumb after changing name
                     this.updateComponentNameInBreadcrumbs();
                 }
             };
@@ -372,49 +562,215 @@ export class GeneralViewModel {
                     && !this.$scope.editForm["componentName"].$error.pattern
                     && (!this.$scope.originComponent.name || this.$scope.component.name.toUpperCase() !== this.$scope.originComponent.name.toUpperCase())
                 ) {
-                    if (!(this.$scope.componentType === ComponentType.RESOURCE && (<Resource>this.$scope.component).csarUUID !== undefined)
+                    if (!(this.$scope.componentType === ComponentType.RESOURCE && (this.$scope.component as Resource).csarUUID !== undefined)
                     ) {
                         this.$scope.component.validateName(name, subtype).then(onSuccess, onFailed);
                     }
-                } else if (this.$scope.originComponent.name && this.$scope.component.name.toUpperCase() === this.$scope.originComponent.name.toUpperCase()) {
+                } else if (this.$scope.editForm && this.$scope.originComponent.name && this.$scope.component.name.toUpperCase() === this.$scope.originComponent.name.toUpperCase()) {
                     // Clear the error
-                    this.$scope.editForm["componentName"].$setValidity('nameExist', true);
+                    this.$scope.editForm['componentName'].$setValidity('nameExist', true);
                 }
             }
         };
 
-        this.$scope.$watchCollection('component.name', (newData:any):void => {
+
+        this.EventListenerService.registerObserverCallback(EVENTS.ON_LIFECYCLE_CHANGE_WITH_SAVE, (nextState) => {
+            if (this.$state.current.data.unsavedChanges && this.$scope.isValidForm) {
+                this.$scope.save().then(() => {
+                    this.$scope.handleChangeLifecycleState(nextState);
+                }, () => {
+                    console.error('Save failed, unable to change lifecycle state to ' + nextState);
+                });
+            } else if(!this.$scope.isValidForm){
+                console.error('Form is not valid');
+            } else {
+                let newCsarVersion:string;
+                if(this.$scope.unsavedFile) {
+                    newCsarVersion = (this.$scope.component as Resource).csarVersion;
+                }
+                if(this.$stateParams.componentCsar && !this.$scope.isCreateMode()) {
+                    const onError = (): void => {
+                        if (this.$scope.component.lifecycleState === 'NOT_CERTIFIED_CHECKIN') {
+                            this.$scope.revert();
+                        }
+                    };
+                    this.$scope.handleChangeLifecycleState(nextState, newCsarVersion, onError);
+
+                } else {
+                    this.$scope.handleChangeLifecycleState(nextState, newCsarVersion);
+                }
+            }
+        });
+
+        this.$scope.revert = ():void => {
+            // in state of import file leave the file in place
+
+            this.$scope.setComponent(this.ComponentFactory.createComponent(this.$scope.originComponent));
+
+            if (this.$scope.component.isResource() && this.$scope.restoreFile) {
+                (this.$scope.component as Resource).importedFile = angular.copy(this.$scope.restoreFile);
+            }
+
+            this.setImportedFileText();
+            this.$scope.updateBreadcrumbs(this.$scope.component); // update on workspace
+
+            this.$scope.componentCategories.selectedCategory = this.$scope.originComponent.selectedCategory;
+            this.setUnsavedChanges(false);
+            this.$scope.updateUnsavedFileFlag(false);
+            this.$scope.editForm.$setPristine();
+        };
+
+        this.$scope.onImportFileChange = () => {
+
+            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
+                this.$scope.restoreFile && !angular.equals(this.$scope.restoreFile, this.$scope.editForm.fileElement.value)){ // or file was swapped for a new one
+                this.$scope.updateUnsavedFileFlag(true);
+            } else {
+                this.$scope.updateUnsavedFileFlag(false);
+                this.$scope.editForm.fileElement.$setPristine();
+            }
+        };
+
+        this.$scope.$watchCollection('component.name', (newData: any): void => {
             this.$scope.validateName(false);
         });
 
         // Notify the parent if this step valid or not.
-        this.$scope.$watch("editForm.$valid", (newVal, oldVal) => {
+        this.$scope.$watch('editForm.$valid', (newVal, oldVal) => {
             this.$scope.setValidState(newVal);
         });
 
-        this.$scope.$watch("editForm.$dirty", (newVal, oldVal) => {
-            if (newVal !== oldVal) {
-                this.$state.current.data.unsavedChanges = newVal && !this.$scope.isCreateMode();
+        this.$scope.$watch('editForm.$dirty', (newVal, oldVal) => {
+            if (newVal && !this.$scope.isCreateMode()) {
+                this.setUnsavedChanges(true);
             }
+
         });
 
-        this.$scope.onCategoryChange = ():void => {
+        this.$scope.onCategoryChange = (): void => {
             this.$scope.component.selectedCategory = this.$scope.componentCategories.selectedCategory;
             this.$scope.component.categories = this.convertCategoryStringToOneArray();
             this.$scope.component.icon = DEFAULT_ICON;
+            if (this.$scope.component.categories[0].metadataKeys) {
+                for (let metadataKey of this.$scope.component.categories[0].metadataKeys) {
+                    if (!this.$scope.component.categorySpecificMetadata[metadataKey.name]) {
+                        this.$scope.component.categorySpecificMetadata[metadataKey.name] = metadataKey.defaultValue ? metadataKey.defaultValue : "";
+                   }
+                }
+            }
+            if (this.$scope.component.categories[0].subcategories && this.$scope.component.categories[0].subcategories[0].metadataKeys) {
+                for (let metadataKey of this.$scope.component.categories[0].subcategories[0].metadataKeys) {
+                    if (!this.$scope.component.categorySpecificMetadata[metadataKey.name]) {
+                        this.$scope.component.categorySpecificMetadata[metadataKey.name] = metadataKey.defaultValue ? metadataKey.defaultValue : "";
+                   }
+                }
+            }
+            if (this.$scope.componentType === ComponentType.SERVICE && this.$scope.component.categories[0]) {
+                   this.elementService.getCategoryBasetypes(this.$scope.component.categories[0].name).subscribe((data: BaseTypeResponse[]) => {
+               
+                    if(this.$scope.isCreateMode()){
+                        this.$scope.baseTypes = []
+                        this.$scope.baseTypeVersions = []
+                        data.forEach(baseType => this.$scope.baseTypes.push(baseType.toscaResourceName));
+                        data[0].versions.reverse().forEach(version => this.$scope.baseTypeVersions.push(version));
+                        this.$scope.component.derivedFromGenericType = data[0].toscaResourceName;
+                        this.$scope.component.derivedFromGenericVersion = data[0].versions[0];
+                    } else {
+                        var isValidForBaseType:boolean = false;
+                        data.forEach(baseType => {if (!this.$scope.component.derivedFromGenericType || baseType.toscaResourceName === this.$scope.component.derivedFromGenericType){
+                            isValidForBaseType = true;
+                        };});
+                        this.$scope.editForm['category'].$setValidity('validForBaseType', isValidForBaseType);
+                    }
+                });
+            }   
         };
 
-        this.$scope.onEcompGeneratedNamingChange = ():void =>{
-            if(!(<Service>this.$scope.component).ecompGeneratedNaming){
-                (<Service>this.$scope.component).namingPolicy = '';
+        this.$scope.onEcompGeneratedNamingChange = (): void => {
+            if (!(this.$scope.component as Service).ecompGeneratedNaming) {
+                (this.$scope.component as Service).namingPolicy = '';
             }
         };
 
-        this.$scope.onVendorNameChange = (oldVendorName:string):void => {
+        this.$scope.onBaseTypeChange = (): void => {
+            this.elementService.getCategoryBasetypes(this.$scope.component.categories[0].name).subscribe((data: BaseTypeResponse[]) => {
+                     this.$scope.baseTypeVersions = []
+                     data.forEach(baseType => {
+                            if(baseType.toscaResourceName === this.$scope.component.derivedFromGenericType) {
+                                    baseType.versions.reverse().forEach(version => this.$scope.baseTypeVersions.push(version));
+                             this.$scope.component.derivedFromGenericVersion = baseType.versions[0];
+                            };
+                     });
+             })
+        };
+
+        this.$scope.onVendorNameChange = (oldVendorName: string): void => {
             if (this.$scope.component.icon === oldVendorName) {
                 this.$scope.component.icon = DEFAULT_ICON;
             }
         };
-        this.EventListenerService.registerObserverCallback(EVENTS.ON_CHECKOUT, this.$scope.reload);
-    };
+        this.EventListenerService.registerObserverCallback(EVENTS.ON_LIFECYCLE_CHANGE, this.$scope.reload);
+
+
+        this.$scope.isMetadataKeyMandatory = (key: string): boolean => {
+            let metadataKey = this.getMetadataKey(this.$scope.component.categories, key);
+            return metadataKey && metadataKey.mandatory;
+        }
+
+        this.$scope.getMetadataKeyValidValues = (key: string): string[] => {
+            let metadataKey = this.getMetadataKey(this.$scope.component.categories, key);
+            if (metadataKey) {
+                return metadataKey.validValues;
+            }
+            return []; 
+        }
+
+        this.$scope.isMetadataKeyForComponentCategory = (key: string): boolean => {
+            return this.getMetadataKey(this.$scope.component.categories, key) != null;
+        }
+
+        this.$scope.isCategoryServiceMetadataKey = (key: string): boolean => {
+            return this.isServiceMetadataKey(key);
+        }
+
+        this.$scope.isMetadataKeyForComponentCategoryService = (key: string, attribute: string): boolean => {
+            let metadatakey = this.getMetadataKey(this.$scope.component.categories, key);
+            if (metadatakey && (!this.$scope.component[attribute] || !metadatakey.validValues.find(v => v === this.$scope.component[attribute]))) {
+                this.$scope.component[attribute] = metadatakey.defaultValue;
+            }
+            return metadatakey != null;
+         }
+    }
+
+    private setUnsavedChanges = (hasChanges: boolean): void => {
+        this.$state.current.data.unsavedChanges = hasChanges;
+    }
+
+    private getMetadataKey(categories: IMainCategory[], key: string) : IMetadataKey {
+        let metadataKey = this.getSubcategoryMetadataKey(this.$scope.component.categories, key);
+        if (!metadataKey){
+            return this.getCategoryMetadataKey(this.$scope.component.categories, key);
+        }
+        return metadataKey;
+    }
+
+    private getSubcategoryMetadataKey(categories: IMainCategory[], key: string) : IMetadataKey {
+           if (categories[0].subcategories && categories[0].subcategories[0].metadataKeys && categories[0].subcategories[0].metadataKeys.some(metadataKey => metadataKey.name == key)) {
+            return categories[0].subcategories[0].metadataKeys.find(metadataKey => metadataKey.name == key);
+        }
+        return null;
+    }
+
+    private getCategoryMetadataKey(categories: IMainCategory[], key: string) : IMetadataKey {
+           if (categories[0].metadataKeys && categories[0].metadataKeys.some(metadataKey => metadataKey.name == key)) {
+            return categories[0].metadataKeys.find(metadataKey => metadataKey.name == key);
+        }
+        return null;
+    }
+
+    private isServiceMetadataKey(key: string) : boolean {
+        return CATEGORY_SERVICE_METADATA_KEYS.indexOf(key) > -1;
+    }
+
 }
+