import { Component, OnInit, Inject } from '@angular/core';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material';
import { FormGroup, FormBuilder } from '@angular/forms';
import { ApplicationSettings } from '@xdf/layouts';
import { BytebotSettingsService } from 'projects/bytebot-html/src/app/services/bytebot-settings-service';

@Component({
  selector: 'byte-es-steps-processors-modal',
  templateUrl: './es-steps-processors-modal.component.html',
  styleUrls: ['./es-steps-processors-modal.component.scss']
})
export class EsStepsProcessorsModalComponent implements OnInit {

  public applicationSettings: ApplicationSettings;

  fields: Array<any> = [];
  formGroup: FormGroup;
  processors: Array<any>;

  constructor(
    public dialogRef: MatDialogRef<EsStepsProcessorsModalComponent>,
    private formBuilder: FormBuilder,
    private bytebotSettingsService: BytebotSettingsService,
    @Inject(MAT_DIALOG_DATA) public data: any) {

    this.processors = data.processors;

    if (!this.processors) {
      this.processors = [];
    }

    for (let processor of this.processors) {

      if (data.connectionProcessors) {
        let found = false;

        for (let connectionProcessor of data.connectionProcessors) {
          if (processor.processorId === connectionProcessor.processorId) {
            found = true;
            processor.hidden = true;
            break;
          }
        }

        if (!found) {
          processor.hidden = false;
        }
      } else {
        processor.hidden = false;
      }

    }

    this.formGroup = this.formBuilder.group({
      processor: null,
      name: null,
      description: null
    });

  }

  ngOnInit() {
    this.bytebotSettingsService.getApplicationSettings().subscribe(result => {
      this.applicationSettings = result;
    });
  }

  selectionChange($event) {
    this.formGroup.patchValue({
      name: $event.value.name,
      description: $event.value.secundaryDescription
    });
  }

  ok() {

    if (this.formGroup.valid) {
      this.dialogRef.close(this.formGroup.controls.processor.value);
    }

  }

}
