// Angular Core
import { Component, Input, OnDestroy, OnInit } from '@angular/core';
import { FormGroup, FormGroupDirective } from '@angular/forms';

// RxJs
import { Subscription } from 'rxjs';

// Services
import { MainSettingsService } from 'src/app/services/mainSettings/main-settings.service';

// Interfaces
import { SuppliersMainSettingsInterface } from 'src/app/interfaces/supplier/suppliers-main-settings-interface';

@Component({
  standalone: false,
  selector: 'app-gcr-settings',
  templateUrl: './gcr-settings.component.html',
  styleUrls: ['./gcr-settings.component.scss']
})
export class GcrSettingsComponent implements OnInit, OnDestroy {

  @Input() supplierData!:SuppliersMainSettingsInterface['data']['supplierData'];
  @Input() formGroupName!:string;

  show_gcr_error_msg: boolean = false;
  gcrtSettingsForm!: FormGroup;
  gcrRatioEnabled!: boolean | number;
  errMsgListener!:Subscription
  

  constructor(
    private mainSettings : MainSettingsService,
    private rootForm:FormGroupDirective,
  ) { }

  ngOnInit(): void {  
    this.errMsgListener = this.mainSettings.toggleErrorMsg.subscribe((data:boolean) => {
        this.show_gcr_error_msg = !data;
    });
    this.gcrtSettingsForm = this.rootForm.control.get(this.formGroupName) as FormGroup;
    this.gcrSettingsFormUpdate();
  }

  get gcrSettingsFormData() { return this.gcrtSettingsForm.controls; }

  gcrSettingsFormUpdate(){
    setTimeout(() => {
        this.gcrtSettingsForm.patchValue({
            gcr_ratio_enabled : this.supplierData.gcr_ratio_enabled,
            generics_ratio : this.supplierData.generics_ratio,
            brands_ratio : this.supplierData.brands_ratio,
            include_otc : this.supplierData.include_otc,
            include_other : this.supplierData.include_other,
        })
        this.gcrRatioEnabled = this.supplierData.gcr_ratio_enabled;
        this.toggleDisabledFieldsIngcrSettingsForm();
    }, 2000);
  }

  toggleDisabledFieldsIngcrSettingsForm(){
    this.gcrRatioEnabled = !this.gcrRatioEnabled;
    
    if(!this.gcrRatioEnabled){
      this.gcrtSettingsForm.get("generics_ratio")?.enable();
      this.gcrtSettingsForm.get("brands_ratio")?.enable();
      this.gcrtSettingsForm.get("include_otc")?.enable();
      this.gcrtSettingsForm.get("include_other")?.enable();
    } else {
      this.gcrtSettingsForm.get("generics_ratio")?.disable();
      this.gcrtSettingsForm.get("brands_ratio")?.disable();
      this.gcrtSettingsForm.get("include_otc")?.disable();
      this.gcrtSettingsForm.get("include_other")?.disable();
    }
  }

  ngOnDestroy() {
    this.errMsgListener?.unsubscribe();
  }

  updateFormData() {
    Object.keys(this.gcrtSettingsForm.controls).forEach(controlName => {
        this.supplierData[controlName] = this.gcrtSettingsForm.controls[controlName].value;
    });
  }

}
