import * as $ from "jquery";
import { InobyModule } from "@lib/inoby-module";
import { WpbsFormExtendDatepicker } from "./modules/wpbs-form-extend-datepicker";

class WpbsFormExtend extends InobyModule {
  run() {
    this.fillCapacityInput();

    if (window.inoby_vars?.wpbs_extend?.datepicker) {
      $(".wpbs-main-wrapper").each(function () {
        new WpbsFormExtendDatepicker($(this)).init();
      })
    }
  }

  /**
   * Fill capacity input in wpbs reservation form
   * with the value from query string
   */
  private fillCapacityInput(): void {
    const hasCapacityInput = $(".wpbs-main-wrapper .wpbs-form-field-capacity").length > 0;

    if (hasCapacityInput) {
      const qCapacity = this.getCapacityFromQueryString();
      if (qCapacity !== null) {
        $(".wpbs-main-wrapper .wpbs-form-field-capacity").find("input").val(qCapacity);
      }
    }
  }

  /**
   * Get capacity from query string
   *
   * @returns Capacity or null if query string is empty
   */
  private getCapacityFromQueryString(): number {
    const params = new URLSearchParams(window.location.search);
    const capacityStr = params.get("wpbs-capacity");
    if (capacityStr?.length) {
      return Number.parseInt(capacityStr);
    }

    return null;
  }
}

new WpbsFormExtend().runOnReady();
