import { Component, OnInit, Input, ElementRef } from "@angular/core"
import { FormGroup } from "@angular/forms"

@Component({
  selector: "app-investment-origin",
  templateUrl: "./investment-origin.component.html",
  styleUrls: ["./investment-origin.component.scss"]
})
export class InvestmentOriginComponent implements OnInit {
  @Input() form: FormGroup
  hasExtras = false
  extrasValue = ""

  constructor(private myElement: ElementRef) {}

  ngOnInit(): void {
    const element = this.myElement.nativeElement as Element
    function listenCheckboxEvents(form: FormGroup, selector: string, control: string) {
      const checkbox = element.querySelector(`duet-checkbox[label='${selector}']`) as HTMLDuetSelectElement
      checkbox.addEventListener("duetChange", (e: CustomEvent<{checked: boolean}>) => {
        form.controls[control].setValue(e.detail.checked)
      })
    }
    listenCheckboxEvents(this.form, 'Valinta 1', 'salary')
    listenCheckboxEvents(this.form, 'Valinta 2', 'gift')
    listenCheckboxEvents(this.form, 'Valinta 3', 'heritage')
    listenCheckboxEvents(this.form, 'Valinta 4', 'entrepreneurialIncome')
    listenCheckboxEvents(this.form, 'Valinta 5', 'assets')
    listenCheckboxEvents(this.form, 'Valinta 6', 'otherIncome')
  }

  handleExtrasChange(event: CustomEvent) {
    this.hasExtras = event.detail.checked

    if (!event.detail.checked) {
      this.form.get("extras").setValue(null)
    }
  }

  handleExtrasValueChange(event: CustomEvent) {
    this.extrasValue = event.detail.value
    this.form.get("extras").setValue(this.extrasValue)
  }
}
