Merge "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             this.sourcesOptions = [];
70             for (let key in this.sources) {
71                let source = {
72                   name: key,
73                   data: this.sources[key]
74                }
75                this.sourcesOptions.push(source);
76             }
77          })
78    }
79
80    onChange(item, $event) {
81       var editedData = JSON.parse($event.srcElement.value);
82       var originalSources = this.resources.definition.sources;
83       for (let key in originalSources) {
84          if (key == item.name) {
85             originalSources[key] = editedData;
86          }
87       }
88       this.resources.definition.sources = Object.assign({}, originalSources);
89
90       let resourcesState = {
91          resources: this.resources,
92          isLoadSuccess: true,
93          isUpdateSuccess: true,
94          isSaveSuccess: true
95       }
96       this.store.dispatch(new SetResourcesState(resourcesState));
97    };
98
99    // to remove this method
100    selected(sourceValue) {
101       this.sourcesData = [];//this.sources[value];
102       this.apiService.getModelType(sourceValue.value)
103          .subscribe(data => {
104             console.log(data);
105             data.forEach(item => {
106                if (typeof (item) == "object") {
107                   for (let key1 in item) {
108                      if (key1 == 'properties') {
109                         let newPropOnj = {}
110                         for (let key2 in item[key1]) {
111                            console.log(item[key1][key2]);
112                            let varType = item[key1][key2].type
113                            // let property :  varType = 
114                            newPropOnj[key2] = item[key1][key2];
115                         }
116                      }
117                   }
118                }
119             });
120             this.sourcesData = data;
121             this.sourcesOptions.forEach(item => {
122                if (item.name == sourceValue.name) {
123                   item.data = data;
124                }
125             })
126             return this.sourcesData;
127          })
128    }
129
130    delete(item, i) {
131       if (confirm("Are sure you want to delete this source ?")) {
132          var originalSources = this.resources.definition.sources;
133          for (let key in originalSources) {
134             if (key == item.name) {
135                delete originalSources[key];
136             }
137          }
138          this.resources.definition.sources = Object.assign({}, originalSources);
139          this.sourcesOptions.splice(i, 1);
140          if (!this.checkIfSourceExists(this.option, item.name)) {
141             this.tempOption.forEach(tempOptionitem => {
142                if (tempOptionitem.name == item.name) {
143                   this.option.push(tempOptionitem);
144                }
145             });
146          }
147          let newsources = {};
148          this.sourcesOptions.forEach(sourceItem => {
149             newsources[sourceItem.name] = {};
150             newsources[sourceItem.name] = sourceItem.data;
151          });
152          this.resources.definition.sources = newsources;
153          let resourcesState = {
154             resources: this.resources,
155             isLoadSuccess: true,
156             isUpdateSuccess: true,
157             isSaveSuccess: true
158          }
159          this.store.dispatch(new SetResourcesState(resourcesState));
160       }
161    }
162
163    UploadSourcesData() {
164       this.resourcesData.emit(this.resources);
165    }
166
167    drop(event: CdkDragDrop<string[]>) {
168       if (!this.checkIfSourceExists(this.sourcesOptions, event.item.element.nativeElement.innerText)) {
169          if (event.previousContainer === event.container) {
170             moveItemInArray(event.container.data, event.previousIndex, event.currentIndex);
171          } else {
172             transferArrayItem(event.previousContainer.data,
173                event.container.data,
174                event.previousIndex,
175                event.currentIndex);
176          }
177          this.tempOption.forEach((item) => {
178             if (item.name == event.item.element.nativeElement.innerText) {
179                this.apiService.getModelType(item.value)
180                   .subscribe(data => {
181                      console.log(data);
182                      data.forEach(dataitem => {
183                         if (typeof (dataitem) == "object") {
184                            for (let key1 in dataitem) {
185                               if (key1 == 'properties') {
186                                  let newPropObj = {};
187                                  newPropObj["name"] = event.item.element.nativeElement.innerText;
188                                  newPropObj['data'] = {};
189                                  let newSoruceObj = {};
190                                  for (let key2 in dataitem[key1]) {
191                                     newSoruceObj[key2] = '';;
192                                  }
193                                  newPropObj['data']['properties'] = newSoruceObj;
194                                  this.sourcesOptions.forEach(sourcesOptionsitem => {
195                                     if (sourcesOptionsitem.name == item.name) {
196                                        sourcesOptionsitem.data = newPropObj['data'];
197                                     }
198                                  });
199                               }
200                            }
201                         }
202                      });
203                      let newsources = {};
204                      this.sourcesOptions.forEach(sourceItem => {
205                         console
206                         newsources[sourceItem.name] = {};
207                         newsources[sourceItem.name] = sourceItem.data;
208                      });
209                      this.resources.definition.sources = newsources;
210                      let resourcesState = {
211                         resources: this.resources,
212                         isLoadSuccess: true,
213                         isUpdateSuccess: true,
214                         isSaveSuccess: true
215                      }
216                      this.store.dispatch(new SetResourcesState(resourcesState));
217                   });
218             }
219          });
220       }
221    }
222
223    getResources() {
224       this.apiService.getSources()
225          .subscribe(data => {
226             console.log(data);
227             for (let key in data[0]) {
228                let sourceObj = { name: key, value: data[0][key] }
229                this.option.push(sourceObj);
230                this.tempOption.push(sourceObj);
231             }
232          }, error => {
233             console.log(error);
234          })
235    }
236
237    checkIfSourceExists(sourceList, sourceName) {
238       let sourceExists: boolean = false;
239       sourceList.forEach(item => {
240          if (item.name == sourceName) {
241             sourceExists = true;
242          }
243       });
244       return sourceExists;
245    }
246 }