import PlaceablePaletteMixin from "./placeable-palette-mixin.mjs";
import DrawingConfig from "../drawing-config.mjs";
import DrawingDocument from "@client/documents/drawing.mjs";
import FontConfig from "@client/applications/settings/menus/font-config.mjs";

/**
 * A dialog that provides bulk operation or default values for newly-created drawings.
 * @extends {DrawingConfig}
 * @mixes PlaceablePaletteMixin
 */
export default class DrawingPalette extends PlaceablePaletteMixin(DrawingConfig) {
  /** @override */
  static DEFAULT_OPTIONS = {
    id: "drawing-palette",
    initialData: { shape: { type: "p", width: 1, height: 1, points: [0, 0, 1, 0] } }
  };

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

  /**
   * The setting key where default data is saved.
   * @type {string}
   */
  static SETTING_KEY = "drawingPalette";

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

  /**
   * The placeable document.
   * @type {string}
   */
  static documentName = "Drawing";

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

  /** @override */
  static TABS = {};

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

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

  /* -------------------------------------------- */
  /*  Properties                                  */
  /* -------------------------------------------- */

  /** @override */
  static get schema() {
    const fullSchema = DrawingDocument.defineSchema();
    const allowed = new Set(DrawingDocument.defaultDrawingFields);
    const fields = {};
    for ( const key of allowed ) fields[key] = fullSchema[key];
    fields.bezierFactor.initial = 0.5;
    return new foundry.data.fields.SchemaField(fields);
  }

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

  /** @inheritDoc */
  async _prepareContext(options) {
    const context = await super._prepareContext(options);
    context.isFreehand = game.activeTool === "freehand";
    context.scaledBezierFactor = context.source.bezierFactor * 2;
    context.fillDisabled = context.source.fillType === CONST.DRAWING_FILL_TYPES.NONE;
    context.fillTypes = Object.entries(CONST.DRAWING_FILL_TYPES).map(([k, v]) => ({
      value: v, label: _loc(`DRAWING.FILL_TYPES.${k.toLowerCase()}`)
    }));
    context.fontFamilies = FontConfig.getAvailableFontChoices();
    context.drawingRoles = { false: _loc("DRAWING.Object"), true: _loc("DRAWING.Information") };
    return context;
  }

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

  /** @override */
  async _preparePartContext(partId, context, options) {
    context.partId = `${this.id}-${partId}`;
    return context;
  }

  /* -------------------------------------------- */
  /*  Deprecations & Compatibility                */
  /* -------------------------------------------- */

  /**
   * Migrate existing default drawing settings into the palette.
   * @internal
   */
  static _migrateDefaultDrawingConfig() {
    const storage = game.settings.storage.get("client");
    const oldData = storage?.getItem("core.defaultDrawingConfig");
    if ( !oldData ) return;
    try {
      const parsed = JSON.parse(oldData);
      if ( !foundry.utils.isEmpty(parsed) ) {
        const newKey = `core.${this.SETTING_KEY}`;
        if ( !storage.getItem(newKey) ) storage.setItem(newKey, JSON.stringify(parsed));
      }
      storage.removeItem("core.defaultDrawingConfig");
    } catch(e) {
      console.warn("Failed to migrate defaultDrawingConfig to drawingPalette", e);
    }
  }
}
