All files / src/app/components/view-builder view-builder.component.ts

74.19% Statements 69/93
69.56% Branches 32/46
76.47% Functions 13/17
72.72% Lines 64/88

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243                              37x 2x 2x 2x     2x       2x 2x 2x   2x 2x 2x       2x         2x 2x 2x 1x   1x 1x 1x 1x                           2x 2x                                                           1x         1x     1x         1x                           2x       2x 2x 2x   2x 2x 1x     1x   2x                           2x 2x 1x   1x               1x   1x 1x 1x                     1x 1x   1x 1x 1x                           2x 2x 2x     2x       2x       2x 2x       2x       2x 4x         2x         2x 2x 2x 1x     2x                
import { Component, OnInit } from '@angular/core';
import { FormsModule, ReactiveFormsModule, FormGroup, FormBuilder, FormControl } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { DynamicComponentService } from '../../services/dynamic-component.service';
import { CustomView } from '../../models/customView';
import { MessageService } from 'primeng/api';
import { NgIf } from '@angular/common';
 
@Component({
  selector: 'app-view-builder',
  imports: [FormsModule, ReactiveFormsModule, NgIf],
  templateUrl: './view-builder.component.html',
  styleUrl: './view-builder.component.css'
})
 
export class ViewBuilderComponent implements OnInit {
  isNameErrorVisible: boolean = false;
  isConfErrorVisible: boolean = false;
  isDataErrorVisible: boolean = false;
  userId: string;
  viewId: string;
  buildedView: CustomView = new CustomView();
  customViewForm: FormGroup;
  configurationText: string;
  componentText: string;
  jsonConfiguration: any = {}; // eslint-disable-line  @typescript-eslint/no-explicit-any
  jsonComponent: any = {}; // eslint-disable-line @typescript-eslint/no-explicit-any
  error: string = '';
 
  constructor(private fb: FormBuilder, private route: ActivatedRoute, private dynamicComponentService: DynamicComponentService, private messageService: MessageService, private router: Router){
    this.userId = this.route.snapshot.params['user_id'] || null;
    this.viewId = this.route.snapshot.params['view_id'] || null;
  }
 
  ngOnInit(): void {
    this.customViewForm = this.fb.group({
      customViewName: new FormControl(),
      customViewConfiguration: new FormControl(),
      componentExample: new FormControl()
    });
    this.jsonConfiguration = [];
    this.configurationText = JSON.stringify(this.jsonConfiguration, null, 4);
    if(this.viewId !== null){
      this.dynamicComponentService.getCustomViewById(this.viewId).subscribe({
        next: value => {
          Eif(value !== null) {
            this.buildedView = value;
            this.customViewForm.get('customViewName')?.setValue(value.name);
            this.customViewForm.get('customViewConfiguration')?.setValue(JSON.stringify(value.configuration, null, 4));
          }
          else {
            this.router.navigate(['/customViews']);
          }
        },
        error: error => {
          console.log(error);
        }
      });
    }
  }
 
  newComponent(newValue: Event){
    const componentSelected = (newValue.target as HTMLInputElement).value;
    switch(componentSelected) {
      case 'PidComponent': {
        this.jsonComponent = {
          "type": "PidComponent",
          "location": "../pid/pid.component",
          "data": {
            "deviceId": ""
          }
        };
        break;
      }
      case 'PetriComponent': {
        this.jsonComponent = {
          "type": "PetriComponent",
          "location": "../petri/petri.component",
          "data": {
            "deviceId": ""
          }
        };
        break;
      }
      case 'VideosComponent': {
        this.jsonComponent = {
          "type": "VideosComponent",
          "location": "../videos/videos.component",
          "data": {}
        };
        break;
      }
      case 'SignalsComponent': {
        this.jsonComponent = {
          "type": "SignalsComponent",
          "location": "../signals/signals.component",
          "data": {}
        };
        break;
      }
      case 'SignalsGraphsComponent': {
        this.jsonComponent = {
          "type": "SignalsGraphsComponent",
          "location": "../signals-graphs/signals-graphs.component",
          "data": {}
        };
        break;
      }
      case 'EventsComponent': {
        this.jsonComponent = {
          "type": "EventsComponent",
          "location": "../events/events.component",
          "data": {}
        };
        break;
      }
      default: {
        break;
     }
    }
    this.componentText = JSON.stringify(this.jsonComponent, null, 4);
  }
 
  addToConfiguration(){
    this.error = '';
    const brackPos = this.configurationText.lastIndexOf("]");
    let jsonConfigurationFile = this.configurationText.slice(0, brackPos);
 
    try {
      if(jsonConfigurationFile[jsonConfigurationFile.length - 2] === "}"){
        jsonConfigurationFile += "," + this.componentText + "]";
      }
      else {
        jsonConfigurationFile += this.componentText + "]";
      }
      this.configurationText = JSON.stringify(JSON.parse(jsonConfigurationFile), null, 4);
    }
    catch(error){
      console.log('error', error);
      if (error instanceof SyntaxError) { // check if it's a SyntaxError
        this.error = error.message; // store the error message in a string variable
      }
      else {
        console.error('Unknown error occurred:', error);
      }
    }
  }
 
  saveCustomView(){
    Eif(this.buildView()){
      if(this.viewId !== null){
        this.dynamicComponentService.updateCustomView(this.buildedView).subscribe({
          next: _ => {
            this.messageService.add({severity: 'success', summary:  'Edit custom view', detail: "Custom view successfully saved" });
          },
          error: error => {
            this.messageService.add({severity: 'error', summary: 'Edit custom view', detail: error.error });
          }
        });
      }
      else{
        this.dynamicComponentService.createCustomView(this.buildedView).subscribe({
          next: value => {
            const responseId = Object.values(value);
            this.messageService.add({severity: 'success', summary:  'Add custom view', detail: "Custom view successfully created" });
            this.router.navigate([`/customViews/${responseId}`]);
          },
          error: error => {
            this.messageService.add({severity: 'error', summary: 'Add custom view', detail: error.error });
          }
        });
      }
    }
  }
 
  deleteCustomView(customViewId: string, customViewName: string){
    Eif(confirm(`Are you sure to delete ${customViewName} ?`)){
      this.dynamicComponentService.deleteCustomView(customViewId).subscribe({
        next: value => {
          Eif(value){
            this.messageService.add({severity: 'success', summary:  'Delete custom view', detail: "Custom view successfully deleted"});
            this.router.navigate(['/customViews']);
          }
          else{
            this.messageService.add({severity: 'error', summary:  'Delete custom view', detail: "An error occurred while deleting this view"});
          }
        },
        error: error => {
          this.messageService.add({severity: 'error', summary:  'Delete custom view', detail: error.error});
        }
      });
    }
  }
 
  buildView(): boolean{
    try{
      const viewName = this.customViewForm.get('customViewName')?.value;
      const viewConfiguration = this.customViewForm.get('customViewConfiguration')?.value;
 
      // Check View Name
      Iif(viewName === null || viewName.length === 0){
        this.isNameErrorVisible = true;
      }
      else{
        this.isNameErrorVisible = false;
      }
 
      // Check View Configurator
      const parsedConf: [] = JSON.parse(viewConfiguration);
      Iif(parsedConf.length === 0){
        this.isConfErrorVisible = true;
      }
      else{
        this.isConfErrorVisible = false;
      }
 
      // Check data values
      this.isDataErrorVisible = parsedConf.some(component =>
        !component['data'] || // If "data" not exist
        (component['data']['deviceId'] === "") // Si "deviceId" est une chaƮne vide
      );
 
      // If one check isn't correct return false
      Iif(this.isNameErrorVisible || this.isConfErrorVisible || this.isDataErrorVisible){
        return false;
      }
 
      // Create custom view object or retrieve it if exist
      this.buildedView.name = viewName;
      this.buildedView.configuration = parsedConf;
      if(this.buildedView.user_id === null || this.buildedView.user_id === undefined){
        this.buildedView.user_id = this.userId;
      }
 
      return true;
    }
    catch(error){
      console.log(error);
      return false;
    }
  }
}