import PlaceableConfig from "./placeable-config.mjs";

/**
 * The Application responsible for configuring a single AmbientSound document within a parent Scene.
 */
export default class AmbientSoundConfig extends PlaceableConfig {

  /** @inheritDoc */
  static DEFAULT_OPTIONS = {
    classes: ["ambient-sound-config"],
    window: {
      contentClasses: ["standard-form"]
    },
    position: {width: 560},
    form: {
      closeOnSubmit: true
    },
    canCreate: true
  };

  /** @override */
  static PARTS = {
    body: {
      template: "templates/scene/ambient-sound-config.hbs"
    },
    footer: {
      template: "templates/generic/form-footer.hbs"
    }
  };

  /* -------------------------------------------- */

  /** @inheritDoc */
  get title() {
    if ( !this.document.id ) return _loc("AMBIENT_SOUND.ACTIONS.CREATE");
    return super.title;
  }

  /* -------------------------------------------- */

  /** @inheritDoc */
  async _prepareContext(options) {
    const context = await super._prepareContext(options);
    return Object.assign(context, {
      soundEffects: CONFIG.soundEffects,
      buttons: [{
        type: "submit",
        icon: "fa-solid fa-floppy-disk",
        label: `AMBIENT_SOUND.ACTIONS.${this.document.collection?.has(this.document.id) ? "UPDATE" : "CREATE"}`
      }]
    });
  }

  /* -------------------------------------------- */

  /** @inheritDoc */
  async _onRender(context, options) {
    this._toggleDisabledFields();
    return super._onRender(context, options);
  }

  /* -------------------------------------------- */
  /*  Real-Time Preview                           */
  /* -------------------------------------------- */


  /** @inheritDoc */
  _onChangeForm(formConfig, event) {
    this._toggleDisabledFields();
    super._onChangeForm(formConfig, event);
  }

  /* -------------------------------------------- */

  /**
   * Special logic to toggle the disabled state of form fields depending on the values of other fields.
   * @protected
   */
  _toggleDisabledFields() {
    const form = this.element;
    form["effects.base.intensity"].disabled = !form["effects.base.type"].value;
    form["effects.muffled.type"].disabled = form.walls.checked;
    form["effects.muffled.intensity"].disabled = form.walls.checked || !form["effects.muffled.type"].value;
  }

  /* -------------------------------------------- */

  /** @inheritDoc */
  _previewChanges(changes) {
    super._previewChanges(changes);
    if ( !this._preview.rendered ) return;
    this._preview.object.initializeSoundSource();
  }
}
