import {ShapeControls} from "@client/canvas/containers/elements/shape-controls.mjs";

/**
 * @import TileDocument from "@client/documents/tile.mjs";
 * @import Tile from "@client/canvas/placeables/tile.mjs";
 * @import TilesLayer from "@client/canvas/layers/tiles.mjs";
 * @import {RectangleShapeData} from "@common/data/_module.mjs";
 */

/**
 * Controls for a Tile shape.
 * @extends {ShapeControls<TileDocument, Tile, TilesLayer, RectangleShapeData>}
 */
export default class TileShapeControls extends ShapeControls {

  /** @inheritDoc */
  _onDragStart(event) {
    super._onDragStart(event);

    // Handle transformation of other controlled tiles
    if ( event.interactionData.handle.name === "translate" ) {
      const others = event.interactionData.others = [];
      for ( const object of this.layer.controlled ) {
        if ( object !== this.object ) others.push(ShapeControls._createDragPreview(object));
      }
    }
  }

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

  /** @override */
  _updateDragPreview(event) {
    const {shape, preview} = event.interactionData;
    const {x, y, width, height, rotation} = shape;
    preview.document.updateSource({x, y, width, height, rotation});
    preview.renderFlags.set({refreshTransform: true});

    // Handle translation of other controlled tiles
    if ( !event.interactionData.others?.length ) return;
    const dx = preview.document.x - this.document.x;
    const dy = preview.document.y - this.document.y;
    for ( const preview of event.interactionData.others ) {
      const {x, y} = preview._original.document._source;
      preview.document.updateSource({x: x + dx, y: y + dy});
      preview.renderFlags.set({refreshPosition: true});
    }
  }

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

  /** @override */
  _prepareDragDropUpdate(event) {
    const {x, y, width, height, rotation} = event.interactionData.preview.document._source;
    return {x, y, width, height, rotation};
  }

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

  /** @inheritDoc */
  _onDragDrop(event) {

    // Handle translation of multiple controlled tiles
    if ( event.interactionData.others?.length ) {
      event.interactionData.clearPreviewContainer = false;
      const {x, y} = event.interactionData.preview.document._source;
      const updates = [{_id: this.document.id, x, y}];
      for ( const preview of event.interactionData.others ) {
        const {x, y} = preview.document._source;
        updates.push({_id: preview._original.document.id, x, y});
      }
      this.document.parent.updateEmbeddedDocuments("Tile", updates).finally(() => {
        this.layer.clearPreviewContainer();
      });
      return;
    }

    return super._onDragDrop(event);
  }

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

  /** @override */
  _onClick2(event) {
    this.document.sheet.render({force: true, tab: "position"});
  }
}
