import Command from '../command';
import { COMMAND_TYPE } from '../constants';

export default class SetPositionCommand extends Command {
  constructor(service, uuid, newPosition, oldPosition) {
    super(service);
    this.type = COMMAND_TYPE.SET_POSITION;
    this.name = '修改位置';
    this.updatable = true;
    this.object = service.getObjectByUuid(uuid);
    this.oldPosition =
      oldPosition && oldPosition.length === 3
        ? new service.THREE.Vector3(oldPosition[0], oldPosition[1], oldPosition[2])
        : this.object
        ? this.object.position.clone()
        : new service.THREE.Vector3();
    this.newPosition = new service.THREE.Vector3(
      Number(newPosition[0]) || 0,
      Number(newPosition[1]) || 0,
      Number(newPosition[2]) || 0
    );
  }

  execute() {
    if (!this.object) return;
    this.object.position.copy(this.newPosition);
    this.object.updateMatrixWorld(true);
  }

  undo() {
    if (!this.object) return;
    this.object.position.copy(this.oldPosition);
    this.object.updateMatrixWorld(true);
  }

  canUpdate(command, deltaTime, mergeWindow) {
    return (
      command &&
      command.type === this.type &&
      this.object &&
      command.object &&
      command.object.uuid === this.object.uuid &&
      deltaTime <= mergeWindow
    );
  }

  update(command) {
    this.newPosition.copy(command.newPosition);
  }

  getChangedKeys() {
    return ['position'];
  }
}
