8c2a11429157667992ede34e7380eca74d877dad
[portal/nonrtric-controlpanel.git] / webapp-frontend / src / app / policy-control / no-type-policy-instance-dialog.component.ts
1 /*-
2  * ========================LICENSE_START=================================
3  * O-RAN-SC
4  * %%
5  * Copyright (C) 2020 Nordix Foundation
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 import { Component, Inject, OnInit } from '@angular/core';
21 import { FormControl, FormGroup, Validators, ValidatorFn, AbstractControl } from '@angular/forms';
22 import { MAT_DIALOG_DATA } from '@angular/material/dialog';
23 import { PolicyService } from '../services/policy/policy.service';
24 import { NotificationService } from '../services/ui/notification.service';
25 import { UiService } from '../services/ui/ui.service';
26 import { HttpErrorResponse } from '@angular/common/http';
27 import { ErrorDialogService } from '../services/ui/error-dialog.service';
28 import * as uuid from 'uuid';
29
30 @Component({
31   selector: 'rd-no-type-policy-instance-dialog',
32   templateUrl: './no-type-policy-instance-dialog.component.html',
33   styleUrls: ['./no-type-policy-instance-dialog.component.scss']
34 })
35 export class NoTypePolicyInstanceDialogComponent implements OnInit {
36   instanceForm: FormGroup;
37
38   policyInstanceId: string; // null if not yet created
39   policyJson: string;
40   darkMode: boolean;
41   ric: string;
42   allRics: string[];
43
44   constructor(
45     private policySvc: PolicyService,
46     private errorService: ErrorDialogService,
47     private notificationService: NotificationService,
48     @Inject(MAT_DIALOG_DATA) private data,
49     private ui: UiService) {
50     this.policyInstanceId = data.instanceId;
51     this.policyJson = data.instanceJson ? this.formatJsonString(data.instanceJson) : '';
52     this.ric = data.ric;
53   }
54
55   ngOnInit() {
56     this.ui.darkModeState.subscribe((isDark) => {
57       this.darkMode = isDark;
58     });
59     this.instanceForm = new FormGroup({
60       'ricSelector': new FormControl(this.ric, [
61         Validators.required
62       ]),
63       'policyJsonTextArea': new FormControl(this.policyJson, [
64         Validators.required,
65         jsonValidator()
66       ])
67     });
68     if (!this.policyInstanceId) {
69       this.fetchRics();
70     }
71   }
72
73   get policyJsonTextArea() { return this.instanceForm.get('policyJsonTextArea'); }
74
75   get ricSelector() { return this.instanceForm.get('ricSelector'); }
76
77   onSubmit() {
78     if (this.policyInstanceId == null) {
79         this.policyInstanceId = uuid.v4();
80     }
81     const self: NoTypePolicyInstanceDialogComponent = this;
82     this.policySvc.putPolicy('', this.policyInstanceId, this.policyJsonTextArea.value, this.ric).subscribe(
83       {
84         next(_) {
85           self.notificationService.success('Policy without type:' + self.policyInstanceId + ' submitted');
86         },
87         error(error: HttpErrorResponse) {
88           self.errorService.displayError('Submit failed: ' + error.error);
89         },
90         complete() { }
91       });
92   }
93
94   private fetchRics() {
95     const self: NoTypePolicyInstanceDialogComponent = this;
96     this.policySvc.getRics('').subscribe(
97       {
98         next(value) {
99           self.allRics = value;
100           console.log(value);
101         },
102         error(error: HttpErrorResponse) {
103           self.errorService.displayError('Fetching of rics failed: ' + error.message);
104         },
105         complete() { }
106       });
107   }
108
109  private formatJsonString(jsonToFormat: string) {
110    return JSON.stringify(JSON.parse(jsonToFormat), null, 2);
111  }
112
113  formatJsonInput() {
114    this.policyJson = this.formatJsonString(this.policyJsonTextArea.value);
115  }
116 }
117
118 export function jsonValidator(): ValidatorFn {
119   return (control: AbstractControl): { [key: string]: any } | null => {
120     const notValid = !isJsonValid(control.value);
121     return notValid ? { 'invalidJson': { value: control.value } } : null;
122   };
123 }
124
125 export function isJsonValid(json: string) {
126   try {
127     if (json != null) {
128       JSON.parse(json);
129       return true;
130     }
131   } catch (jsonError) {
132     return false;
133   }
134 }