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

export default class RemoveElementCommand extends Command {
  constructor(service, uuid) {
    super(service);
    this.type = COMMAND_TYPE.REMOVE_ELEMENT;
    this.name = '删除元素';
    this.object = service.getObjectByUuid(uuid);
    this.parentUuid = this.object && this.object.parent ? this.object.parent.uuid : '';
    this.index = getObjectIndex(this.object);
  }

  execute() {
    if (!this.object) return;
    if (this.object.parent) {
      this.parentUuid = this.object.parent.uuid;
      this.index = getObjectIndex(this.object);
    }
    removeObjectFromParent(this.object);
  }

  undo() {
    if (!this.object) return;
    const parent = this.service.getObjectByUuid(this.parentUuid) || this.service.getCustomRoot();
    insertObjectAt(parent, this.object, this.index);
    this.object.updateMatrixWorld(true);
  }

  toJSON() {
    return {
      ...super.toJSON(),
      uuid: this.object ? this.object.uuid : '',
      parentUuid: this.parentUuid,
      index: this.index,
      object: this.object ? this.object.toJSON() : null,
    };
  }

  fromJSON(json) {
    this.parentUuid = json.parentUuid;
    this.index = json.index;
    this.object = json.object ? this.service.parseObjectJSON(json.object) : null;
  }
}
