import { Component, OnInit } from '@angular/core';
import { IPluginComponent } from '@shared/plugins/interfaces/plugin-component';
import { UntypedFormBuilder, Validators } from '@angular/forms';

@Component({
  selector: 'app-order-product',
  templateUrl: './order-product.component.html',
  styleUrls: ['./order-product.component.scss']
})
export class OrderProductComponent implements OnInit, IPluginComponent {
  orderProdForm = this.formBuilder.group({
    directadmin_license_ip: ['', Validators.required]
  });
  public data: {
    directadmin_license_ip: string;
    valid: boolean;
  };
  backendErrors = {};

  constructor(private formBuilder: UntypedFormBuilder) {
  }

  updateData() {
    this.data.valid = this.orderProdForm.valid;
    if (this.data.valid) {
      this.data.directadmin_license_ip = this.orderProdForm.value.directadmin_license_ip;
    }
  }

  ngOnInit(): void {
    if (this.data.directadmin_license_ip) {
      this.orderProdForm.patchValue(this.data);
    }
    this.updateData();
    this.orderProdForm.valueChanges.subscribe(() => {
      this.updateData();
    });
  }

  setFormErrors(errors: Record<string, any>) {
    this.backendErrors = errors;
    for (const controlName of Object.keys(this.orderProdForm.controls)) {
      const control = this.orderProdForm.controls[controlName];
      if (this.backendErrors[controlName]) {
        control.markAsTouched();
        control.setErrors({backend: true});
      }
    }
  }
}
