import { Component, Inject, OnInit } from '@angular/core';
import { PriorityInterface } from '../system-params.component';
import { FormControl, Validators } from '@angular/forms';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { validColorValidator } from 'ngx-colors';
import { ResourcesService } from '../../../../services/resources.service';

@Component({
    selector: 'app-edit-priority',
    templateUrl: './edit-priority.component.html',
    styleUrl: './edit-priority.component.css',
    standalone: false
})
export class EditPriorityComponent implements OnInit {
  priority: PriorityInterface | null;

  priorityValueControl: FormControl;
  priorityLabelControl: FormControl;
  priorityColorControl: FormControl;
  colorPickerControl: FormControl;

  constructor(
    @Inject(MAT_DIALOG_DATA) private _data: any,
    private _dialogRef: MatDialogRef<EditPriorityComponent>,
    private _resourcesService: ResourcesService,
  ){
    this.priority = null;
    this.priorityValueControl = new FormControl({value: '', disabled: true}, Validators.required);
    this.priorityLabelControl = new FormControl('', Validators.required);
    this.priorityColorControl = new FormControl('', [Validators.required, validColorValidator()]);
    this.colorPickerControl = new FormControl('');
  }

  ngOnInit(): void {
    this.priority = this._data.priority;
    this.priorityValueControl.setValue(this.priority!.value);
    this.priorityLabelControl.setValue(this.priority!.label);
    this.priorityColorControl.setValue(this.priority!.color, {emitEvent: false});
    this.colorPickerControl.setValue(this.priority!.color, {emitEvent: false});

    this.priorityColorControl.valueChanges.subscribe((color) => {
      if(this.priorityColorControl.valid){
        this.colorPickerControl.setValue(color, {
          emitEvent: false,
        });
      }
    });

    this.colorPickerControl.valueChanges.subscribe((color) => {
      this.priorityColorControl.setValue(color, {
        emitEvent: false,
      })
    });
  }

  savePropertyChanges(){
    if(this.priorityValueControl.invalid || this.priorityLabelControl.invalid || this.priorityColorControl.invalid){
      this._resourcesService.openSnackBar('Debe completar los datos obligatorios antes de continuar');
    }else{
      this.priority!.value = this.priorityValueControl.value;
      this.priority!.label = this.priorityLabelControl.value;
      this.priority!.color = this.priorityColorControl.value;

      let res = JSON.stringify(this.priority);
      this._dialogRef.close(res);
    }
  }
}
