import Command from '../command';
import { COMMAND_TYPE } from '../constants';
import { degreesArrayToRadians } from '../scene-helpers';

export default class SetRotationCommand extends Command {
  constructor(service, uuid, newRotation, oldRotation) {
    super(service);
    this.type = COMMAND_TYPE.SET_ROTATION;
    this.name = '修改旋转';
    this.updatable = true;
    this.object = service.getObjectByUuid(uuid);
    const oldRadians = Array.isArray(oldRotation) ? degreesArrayToRadians(oldRotation) : null;
    this.oldRotation =
      oldRadians && oldRadians.length === 3
        ? new service.THREE.Euler(oldRadians[0], oldRadians[1], oldRadians[2], 'XYZ')
        : this.object
        ? this.object.rotation.clone()
        : new service.THREE.Euler();
    const newRadians = degreesArrayToRadians(newRotation);
    this.newRotation = new service.THREE.Euler(newRadians[0], newRadians[1], newRadians[2], 'XYZ');
  }

  execute() {
    if (!this.object) return;
    this.object.rotation.copy(this.newRotation);
    this.object.updateMatrixWorld(true);
  }

  undo() {
    if (!this.object) return;
    this.object.rotation.copy(this.oldRotation);
    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.newRotation.copy(command.newRotation);
  }

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