import { Command } from "./Command.js";

/**
 * 对象移动命令
 * 轻量级命令，只记录对象的移动属性变化（位置）
 */
export class ObjectMoveCommand extends Command {
  constructor(options) {
    super({
      name: options.name || "对象移动",
      description: options.description || "移动对象",
      saveState: false, // 自己管理状态，避免递归
    });

    this.canvas = options.canvas;
    this.initPos = options.initPos;
    this.finalPos = options.finalPos;
  }

  /**
   * 执行命令
   */
  async execute() {
	this.setObjectsPos(this.finalPos);
    return true;
  }
  /**
   * 撤销命令
   * 应用初始状态
   */
  async undo() {
    this.setObjectsPos(this.initPos);
    return true;
  }
  
  async setObjectsPos(pos) {
	const objects = this.canvas.getObjects();
	const arr = typeof pos === "object" ? [pos] : pos;
    arr.forEach((item) => {
      const obj = objects.find((o) => o.id === item.id);
      if(obj) {
        obj.set({
          left: item.left,
          top: item.top,
        });
      }
    });
    this.canvas.renderAll();
  }
}
