import Command from '../command';
import { COMMAND_TYPE } from '../constants';
import { createGeometry, normalizeGeometryParams } from '../element-factory';

export default class SetGeometryParamsCommand extends Command {
  constructor(service, uuid, geometryParams) {
    super(service);
    this.type = COMMAND_TYPE.SET_GEOMETRY_PARAMS;
    this.name = '修改几何参数';
    this.object = service.getObjectByUuid(uuid);
    this.elementType = this.object && this.object.userData ? this.object.userData.elementType : '';
    this.oldParams =
      this.object && this.object.userData && this.object.userData.geometryParams
        ? normalizeGeometryParams(this.elementType, this.object.userData.geometryParams)
        : {};
    this.newParams = normalizeGeometryParams(this.elementType, geometryParams);
    this.oldGeometry = this.object ? this.object.geometry : null;
    this.newGeometry = null;
  }

  execute() {
    if (!this.object) return;
    if (!this.newGeometry) {
      this.newGeometry = createGeometry(this.service.THREE, this.elementType, this.newParams);
    }
    this.object.geometry = this.newGeometry;
    this.object.userData.geometryParams = { ...this.newParams };
    this.object.updateMatrixWorld(true);
  }

  undo() {
    if (!this.object) return;
    this.object.geometry = this.oldGeometry;
    this.object.userData.geometryParams = { ...this.oldParams };
    this.object.updateMatrixWorld(true);
  }

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