Set resource data value when fetch from database
[ccsdk/cds.git] / cds-ui / client / src / app / feature-modules / resource-definition / resource-edit / sources-template / sources-template.component.ts
1 /*
2 * ============LICENSE_START=======================================================
3 * ONAP : CDS
4 * ================================================================================
5 * Copyright (C) 2019 TechMahindra
6 *
7 * Modifications Copyright (C) 2019 IBM
8 *=================================================================================
9 * Licensed under the Apache License, Version 2.0 (the "License");
10 * you may not use this file except in compliance with the License.
11 * You may obtain a copy of the License at
12 *
13 *     http://www.apache.org/licenses/LICENSE-2.0
14 *
15 * Unless required by applicable law or agreed to in writing, software
16 * distributed under the License is distributed on an "AS IS" BASIS,
17 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18 * See the License for the specific language governing permissions and
19 * limitations under the License.
20 * ============LICENSE_END=========================================================
21 */
22
23 import { Component, OnInit, ViewChild, EventEmitter, Output, Input } from '@angular/core';
24 import { CdkDragDrop, moveItemInArray, transferArrayItem } from '@angular/cdk/drag-drop';
25 import { IResources } from 'src/app/common/core/store/models/resources.model';
26 import { IResourcesState } from 'src/app/common/core/store/models/resourcesState.model';
27 import { Observable } from 'rxjs';
28 import { Store } from '@ngrx/store';
29 import { IAppState } from '../../../../common/core/store/state/app.state';
30 import { A11yModule } from '@angular/cdk/a11y';
31 import { SetResourcesState } from 'src/app/common/core/store/actions/resources.action';
32 import { ISourcesData } from 'src/app/common/core/store/models/sourcesData.model';
33 import { JsonEditorComponent, JsonEditorOptions } from 'ang-jsoneditor';
34 import { ResourceEditService } from '../resource-edit.service';
35
36 @Component({
37   selector: 'app-sources-template',
38   templateUrl: './sources-template.component.html',
39   styleUrls: ['./sources-template.component.scss']
40 })
41 export class SourcesTemplateComponent implements OnInit {
42
43     @ViewChild(JsonEditorComponent) editor: JsonEditorComponent;
44     options = new JsonEditorOptions(); 
45     rdState: Observable<IResourcesState>;
46     resources: IResources;
47     option = [];
48     sources:ISourcesData; 
49     sourcesOptions = [];
50     sourcesData = {};
51     @Output() resourcesData = new EventEmitter();
52     tempOption = [];
53  
54     constructor(private store: Store<IAppState>, private apiService: ResourceEditService) {
55     this.rdState = this.store.select('resources');
56     this.options.mode = 'text';
57     this.options.modes = [ 'text', 'tree', 'view'];
58     this.options.statusBar = false;     
59  }
60
61  ngOnInit() {
62     this.rdState.subscribe(
63       resourcesdata => {
64         var resourcesState: IResourcesState = { resources: resourcesdata.resources, isLoadSuccess: resourcesdata.isLoadSuccess, isSaveSuccess: resourcesdata.isSaveSuccess, isUpdateSuccess: resourcesdata.isUpdateSuccess };
65         this.resources=resourcesState.resources;
66          if(resourcesState.resources.definition && resourcesState.resources.definition.sources) {
67          this.sources = resourcesState.resources.definition.sources;
68          }
69         for (let key in this.sources) {
70             let source = {
71                name : key,
72                data: this.sources[key]
73             }
74              this.sourcesOptions.push(source);    
75         }
76     })
77  }
78
79  onChange(item,$event) {
80     var editedData =JSON.parse($event.srcElement.value);
81     var originalSources = this.resources.sources;
82      for (let key in originalSources){
83         if(key == item){
84             originalSources[key] = editedData;
85         }
86      }
87      this.resources.sources = Object.assign({},originalSources);
88  };
89     
90  // to remove this method
91  selected(sourceValue){
92    this.sourcesData= [];//this.sources[value];
93    this.apiService.getModelType(sourceValue.value)
94    .subscribe(data=>{
95       console.log(data);
96       data.forEach(item =>{
97         if(typeof(item)== "object") {
98            for (let key1 in item) {
99               if(key1 == 'properties') {                  
100                  let newPropOnj = {}
101                  for (let key2 in item[key1]) {
102                     console.log(item[key1][key2]);
103                     let varType = item[key1][key2].type
104                     // let property :  varType = 
105                     newPropOnj[key2] = item[key1][key2];
106                  }
107               }
108            }
109         }
110       });
111       this.sourcesData = data;
112       this.sourcesOptions.forEach(item=>{
113          if(item.name == sourceValue.name) {
114             item.data = data;
115          }
116       })       
117      return this.sourcesData;
118    })    
119 }    
120
121  delete(item,i){
122         if(confirm("Are sure you want to delete this source ?")) {
123         var originalSources = this.resources.sources;
124         for (let key in originalSources){
125                 if(key == item){    
126                         delete originalSources[key];
127                 }
128         }
129         this.resources.sources = Object.assign({},originalSources);
130                 this.sourcesOptions.splice(i,1);
131         }     
132  } 
133   
134  UploadSourcesData() {
135         this.resourcesData.emit(this.resources);        
136   }
137     
138  drop(event: CdkDragDrop<string[]>) {
139    if (!this.checkIfSourceExists(event.item.element.nativeElement.innerText)) {
140       if (event.previousContainer === event.container) {
141          moveItemInArray(event.container.data, event.previousIndex, event.currentIndex);
142       } else {
143          transferArrayItem(event.previousContainer.data,
144             event.container.data,
145             event.previousIndex,
146             event.currentIndex);
147       }
148       this.tempOption.forEach((item) => {
149          if (item.name == event.item.element.nativeElement.innerText) {
150             this.apiService.getModelType(item.value)
151                .subscribe(data => {
152                   console.log(data);
153                   data.forEach(dataitem => {
154                      if (typeof (dataitem) == "object") {
155                         for (let key1 in dataitem) {
156                            if (key1 == 'properties') {
157                               let newPropObj = {};
158                               newPropObj["name"] = event.item.element.nativeElement.innerText;
159                               newPropObj['data'] = {};
160                               let newSoruceObj = {};
161                               for (let key2 in dataitem[key1]) {
162                                  newSoruceObj[key2] = '';;
163                               }
164                               newPropObj['data']['properties'] = newSoruceObj;
165                               this.sourcesOptions.forEach(sourcesOptionsitem => {
166                                  if (sourcesOptionsitem.name == item.name) {
167                                     sourcesOptionsitem.data = newPropObj['data'];
168                                  }
169                               });
170                            }
171                         }
172                      }
173                   });
174                   let newsources= {};
175                   this.sourcesOptions.forEach(sourceItem=>{
176                      console
177                      newsources[sourceItem.name] = {};
178                      newsources[sourceItem.name] = sourceItem.data;
179                   });
180                   this.resources.definition.sources = newsources;
181                   let resourcesState = {
182                      resources: this.resources,
183                      isLoadSuccess: true,
184                      isUpdateSuccess:true,
185                      isSaveSuccess:true
186                   }  
187                   this.store.dispatch(new SetResourcesState(resourcesState));
188             });
189          }  
190       });
191    }
192   }
193
194   getResources() {
195    this.apiService.getSources()
196    .subscribe(data=>{
197       console.log(data);
198       for (let key in data[0]) {
199          let sourceObj = { name: key, value: data[0][key] }
200          this.option.push(sourceObj);
201          this.tempOption.push(sourceObj); 
202      }
203    }, error=>{
204       console.log(error);
205    })
206   }
207
208   checkIfSourceExists(sourceName) {
209    let sourceExists: boolean = false;
210    this.sourcesOptions.forEach(item => {
211       if (item.name == sourceName) {
212          sourceExists = true;
213       }
214    });
215    return sourceExists;
216 }
217 }