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

export default class AddElementCommand extends Command {
  constructor(service, object, options = {}) {
    super(service);
    this.type = COMMAND_TYPE.ADD_ELEMENT;
    this.name = '新增元素';
    this.object = object;
    this.parentUuid = options.parentUuid || '';
    this.index = options.index;
  }

  execute() {
    const parent = this.service.getObjectByUuid(this.parentUuid) || this.service.getCustomRoot();
    this.parentUuid = parent.uuid;
    insertObjectAt(parent, this.object, this.index);
    this.index = parent.children.indexOf(this.object);
    this.object.updateMatrixWorld(true);
  }

  undo() {
    removeObjectFromParent(this.object);
  }

  toJSON() {
    return {
      ...super.toJSON(),
      object: this.object.toJSON(),
      parentUuid: this.parentUuid,
      index: this.index,
    };
  }

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