import PlaceableFilter from "./placeable-filter.mjs";

/**
 * An advanced filter dialog for the Tiles placeable tab.
 * @extends {PlaceableFilter}
 */
export default class TileFilter extends PlaceableFilter {
  static DEFAULT_OPTIONS = {
    id: "tile-filter"
  };

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

  /** @override */
  static PARTS = {
    body: {
      root: true,
      classes: ["standard-form"],
      template: "templates/sidebar/filters/tile.hbs"
    }
  };

  /* -------------------------------------------- */
  /*  Rendering                                   */
  /* -------------------------------------------- */

  /** @inheritDoc */
  async _prepareContext(options) {
    const context = await super._prepareContext(options);
    const { SetField, NumberField, BooleanField } = foundry.data.fields;

    // Include NONE to allow filtering for unoccluded tiles.
    const { OCCLUSION_MODES } = CONST;
    const allOcclusionModes = Object.entries(OCCLUSION_MODES).reduce((modes, [k, v]) => {
      modes[v] = `TILE.FIELDS.OCCLUSION_MODES.${k}.label`;
      return modes;
    }, {});
    const { occlusionModes, restrictions } = this.tab._filterState;
    context.occlusion = {
      field: new SetField(
        new NumberField({ choices: allOcclusionModes }),
        { label: "TILE.FIELDS.occlusion.modes.label" },
        { name: "occlusion.modes" }),
      value: occlusionModes
    };
    context.restrictions = {
      light: {
        field: new BooleanField({ label: "TILE.FIELDS.restrictions.light.label" }, { name: "restrictions.light" }),
        value: restrictions.light
      },
      weather: {
        field: new BooleanField({ label: "TILE.FIELDS.restrictions.weather.label" }, { name: "restrictions.weather" }),
        value: restrictions.weather
      }
    };
    return context;
  }

  /* -------------------------------------------- */
  /*  Event Listeners & Handlers                  */
  /* -------------------------------------------- */

  /** @inheritDoc */
  _onChangeForm(formConfig, event) {
    const { target } = event;
    const { restrictions } = this.tab._filterState;
    switch ( target.name ) {
      case "occlusion.modes":
        this.tab._filterState.occlusionModes = new Set(target.value.map(Number));
        break;
      case "restrictions.light": restrictions.light = target.checked; break;
      case "restrictions.weather": restrictions.weather = target.checked; break;
      default: return;
    }
    this.tab._applyFilters();
  }
}
