f167adae7b62cee4728b76f8bd29caea7d2994ef
[portal/nonrtric-controlpanel.git] / webapp-frontend / src / app / policy / no-type-policy-editor / no-type-policy-editor.component.ts
1 // -
2 //   ========================LICENSE_START=================================
3 //   O-RAN-SC
4 //   %%
5 //   Copyright (C) 2021: 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 //
21
22 import { Component, Input, OnInit } from '@angular/core';
23 import { AbstractControl, ControlContainer, FormBuilder, FormControl, FormGroup, FormGroupDirective, ValidatorFn, Validators } from '@angular/forms';
24
25 @Component({
26   selector: 'nrcp-no-type-policy-editor',
27   templateUrl: './no-type-policy-editor.component.html',
28   styleUrls: ['./no-type-policy-editor.component.scss'],
29   viewProviders: [{ provide: ControlContainer, useExisting: FormGroupDirective }]
30 })
31 export class NoTypePolicyEditorComponent implements OnInit {
32
33   @Input() instanceForm: FormGroup;
34   @Input() policyJson: string;
35
36   constructor(
37     private formBuilder: FormBuilder) { }
38
39   ngOnInit(): void {
40     this.instanceForm.addControl(
41       'policyJsonTextArea', new FormControl(this.policyJson, [
42         Validators.required,
43         jsonValidator()
44       ])
45     )
46   }
47
48   get policyJsonTextArea(): AbstractControl {
49     return this.instanceForm ? this.instanceForm.get('policyJsonTextArea') : null;
50   }
51
52   formatJsonInput(): void {
53     this.policyJson = formatJsonString(JSON.parse(this.policyJsonTextArea.value));
54   }
55 }
56
57 export function formatJsonString(jsonToFormat: any): string {
58   return JSON.stringify(jsonToFormat, null, 2);
59 }
60
61 export function jsonValidator(): ValidatorFn {
62   return (control: AbstractControl): { [key: string]: any } | null => {
63     const notValid = !isJsonValid(control.value);
64     return notValid ? { 'invalidJson': { value: control.value } } : null;
65   };
66 }
67
68 export function isJsonValid(json: string): boolean {
69   try {
70     if (json != null) {
71       JSON.parse(json);
72       return true;
73     } else {
74       return false;
75     }
76   } catch (jsonError) {
77     return false;
78   }
79 }