Fixes of the darkMode
[nonrtric.git] / dashboard / webapp-frontend / src / app / policy-control / policy-instance-dialog.component.ts
1 /*-
2  * ========================LICENSE_START=================================
3  * O-RAN-SC
4  * %%
5  * Copyright (C) 2019 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 { animate, state, style, transition, trigger } from '@angular/animations';
21 import { AfterViewInit, Component, Inject, OnInit, ViewChild } from '@angular/core';
22 import { MatDialogConfig, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
23 import { MatMenuTrigger } from '@angular/material/menu';
24 import { JsonPointer } from 'angular6-json-schema-form';
25 import * as uuid from 'uuid';
26 import { PolicyInstance, PolicyType } from '../interfaces/policy.types';
27 import { PolicyService } from '../services/policy/policy.service';
28 import { ErrorDialogService } from '../services/ui/error-dialog.service';
29 import { NotificationService } from './../services/ui/notification.service';
30 import { UiService } from '../services/ui/ui.service';
31
32
33 @Component({
34     selector: 'rd-policy-instance-dialog',
35     templateUrl: './policy-instance-dialog.component.html',
36     styleUrls: ['./policy-instance-dialog.component.scss'],
37     animations: [
38         trigger('expandSection', [
39             state('in', style({ height: '*' })),
40             transition(':enter', [
41                 style({ height: 0 }), animate(100),
42             ]),
43             transition(':leave', [
44                 style({ height: '*' }),
45                 animate(100, style({ height: 0 })),
46             ]),
47         ]),
48     ],
49 })
50 export class PolicyInstanceDialogComponent implements OnInit, AfterViewInit {
51
52     formActive = false;
53     isVisible = {
54         form: true,
55         json: false,
56         schema: false
57     };
58
59     jsonFormStatusMessage = 'Loading form...';
60     jsonSchemaObject: any = {};
61     jsonObject: any = {};
62
63
64     jsonFormOptions: any = {
65         addSubmit: false, // Add a submit button if layout does not have one
66         debug: false, // Don't show inline debugging information
67         loadExternalAssets: true, // Load external css and JavaScript for frameworks
68         returnEmptyFields: false, // Don't return values for empty input fields
69         setSchemaDefaults: true, // Always use schema defaults for empty fields
70         defautWidgetOptions: { feedback: true }, // Show inline feedback icons
71     };
72
73     liveFormData: any = {};
74     formValidationErrors: any;
75     formIsValid = false;
76
77
78     @ViewChild(MatMenuTrigger, { static: true }) menuTrigger: MatMenuTrigger;
79
80     public policyInstanceId: string;
81     public policyTypeName: string;
82     darkMode: boolean;
83     private policyTypeId: number;
84
85
86     constructor(
87         private dataService: PolicyService,
88         private errorService: ErrorDialogService,
89         private notificationService: NotificationService,
90         @Inject(MAT_DIALOG_DATA) private data,
91         private dialogRef: MatDialogRef<PolicyInstanceDialogComponent>,
92         private ui: UiService) {
93         this.formActive = false;
94         this.policyInstanceId = this.data.instanceId;
95         this.policyTypeName = this.data.name;
96         this.policyTypeId = this.data.policyTypeId;
97         this.parseJson(data.createSchema, data.instanceJson);
98     }
99
100     ngOnInit() {
101         this.jsonFormStatusMessage = 'Init';
102         this.formActive = true;
103         this.ui.darkModeState.subscribe((isDark) => {
104             this.darkMode = isDark;
105         });
106     }
107
108     ngAfterViewInit() {
109     }
110
111     onSubmit() {
112         if (this.policyInstanceId == null) {
113             this.policyInstanceId = uuid.v4();
114         }
115         const policyJson: string = this.prettyLiveFormData;
116         const self: PolicyInstanceDialogComponent = this;
117         this.dataService.putPolicy(this.policyTypeId, this.policyInstanceId, policyJson).subscribe(
118             {
119                 next(value) {
120                     self.notificationService.success('Policy ' + self.policyTypeName + ':' + self.policyInstanceId + ' submitted');
121                 },
122                 error(error) {
123                     self.errorService.displayError('updatePolicy failed: ' + error.message);
124                 },
125                 complete() { }
126             });
127     }
128
129     onClose() {
130         this.dialogRef.close();
131     }
132
133     public onChanges(data: any) {
134         this.liveFormData = data;
135     }
136
137     get prettyLiveFormData() {
138         return JSON.stringify(this.liveFormData, null, 2);
139     }
140
141     get schemaAsString() {
142         return JSON.stringify(this.jsonSchemaObject, null, 2);
143     }
144
145     get jsonAsString() {
146         return JSON.stringify(this.jsonObject, null, 2);
147     }
148
149     isValid(isValid: boolean): void {
150         this.formIsValid = isValid;
151     }
152
153     validationErrors(data: any): void {
154         this.formValidationErrors = data;
155     }
156
157     get prettyValidationErrors() {
158         if (!this.formValidationErrors) { return null; }
159         const errorArray = [];
160         for (const error of this.formValidationErrors) {
161             const message = error.message;
162             const dataPathArray = JsonPointer.parse(error.dataPath);
163             if (dataPathArray.length) {
164                 let field = dataPathArray[0];
165                 for (let i = 1; i < dataPathArray.length; i++) {
166                     const key = dataPathArray[i];
167                     field += /^\d+$/.test(key) ? `[${key}]` : `.${key}`;
168                 }
169                 errorArray.push(`${field}: ${message}`);
170             } else {
171                 errorArray.push(message);
172             }
173         }
174         return errorArray.join('<br>');
175     }
176
177     private parseJson(createSchema: string, instanceJson: string): void {
178         try {
179             this.jsonSchemaObject = JSON.parse(createSchema);
180             if (this.data.instanceJson != null) {
181                 this.jsonObject = JSON.parse(instanceJson);
182             }
183         } catch (jsonError) {
184             this.jsonFormStatusMessage =
185                 'Invalid JSON\n' +
186                 'parser returned:\n\n' + jsonError;
187             return;
188         }
189     }
190
191     public toggleVisible(item: string) {
192         this.isVisible[item] = !this.isVisible[item];
193     }
194 }
195
196 export function getPolicyDialogProperties(policyType: PolicyType, instance: PolicyInstance, darkMode: boolean): MatDialogConfig {
197     const policyTypeId = policyType.policy_type_id;
198     const createSchema = policyType.create_schema;
199     const instanceId = instance ? instance.instanceId : null;
200     const instanceJson = instance ? instance.instance : null;
201     const name = policyType.name;
202     return {
203         maxWidth: '1200px',
204         maxHeight: '900px',
205         width: '900px',
206         role: 'dialog',
207         disableClose: false,
208         panelClass: darkMode ? 'dark-theme' : '',
209         data: {
210             policyTypeId,
211             createSchema,
212             instanceId,
213             instanceJson,
214             name
215         }
216     };
217 }
218