import Command from '../command';
import { COMMAND_TYPE } from '../constants';
import { getObjectIndex, insertObjectAt } from '../scene-helpers';

export default class MoveElementCommand extends Command {
  constructor(service, uuid, options = {}) {
    super(service);
    this.type = COMMAND_TYPE.MOVE_ELEMENT;
    this.name = '移动元素';
    this.object = service.getObjectByUuid(uuid);
    this.oldParentUuid = this.object && this.object.parent ? this.object.parent.uuid : '';
    this.oldIndex = getObjectIndex(this.object);
    this.newParentUuid = options.targetParentUuid || '';
    this.newIndex = options.index;
  }

  execute() {
    if (!this.object) return;
    const targetParent =
      this.service.getObjectByUuid(this.newParentUuid) || this.service.getCustomRoot();
    insertObjectAt(targetParent, this.object, this.newIndex);
    this.newParentUuid = targetParent.uuid;
    this.newIndex = targetParent.children.indexOf(this.object);
    this.object.updateMatrixWorld(true);
  }

  undo() {
    if (!this.object) return;
    const oldParent =
      this.service.getObjectByUuid(this.oldParentUuid) || this.service.getCustomRoot();
    insertObjectAt(oldParent, this.object, this.oldIndex);
    this.object.updateMatrixWorld(true);
  }

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

  toJSON() {
    return {
      ...super.toJSON(),
      uuid: this.object ? this.object.uuid : '',
      oldParentUuid: this.oldParentUuid,
      oldIndex: this.oldIndex,
      newParentUuid: this.newParentUuid,
      newIndex: this.newIndex,
    };
  }

  fromJSON(json) {
    this.object = this.service.getObjectByUuid(json.uuid);
    this.oldParentUuid = json.oldParentUuid;
    this.oldIndex = json.oldIndex;
    this.newParentUuid = json.newParentUuid;
    this.newIndex = json.newIndex;
  }
}
