import { Controller } from '@hotwired/stimulus';
import { BUY_FORM_COLLECT_DATA } from '@assets/components/constants/eventTypes';
import { getBuyFormComponent } from '@assets/components/utils';
import { BuyFormCollectDataEvent } from '@assets/components/interfaces';

export default class extends Controller<HTMLDivElement> {
   static targets = ['input'];
   declare inputTarget: HTMLInputElement;

   static values = {
      componentKey: String
   };
   declare componentKeyValue: string;

   private buyForm: Controller;

   collectDataListener = (event: BuyFormCollectDataEvent) => {
      event.setPieces(this.inputTarget.valueAsNumber);
   };

   connect() {
      this.buyForm = getBuyFormComponent(this.application, this.componentKeyValue, this.element);

      if (this.buyForm) {
         this.buyForm.element.addEventListener(BUY_FORM_COLLECT_DATA, this.collectDataListener as EventListener);
      }
   }

   disconnect() {
      if (this.buyForm) {
         this.buyForm.element.removeEventListener(BUY_FORM_COLLECT_DATA, this.collectDataListener as EventListener);
      }
   }
}
