import { TransCreateFn, TransferCtrl } from "..";

function getTransform(this: TransferCtrl, transType: string) {
  const { transEvent, originPiont } = this;
  const { transform = {} } = this.currComp?.layout || {};
  const offset = {
    x: transform.x || 0,
    y: transform.y || 0,
    r: transform.r || 0,
    s: transform.s || 1,
  };

  const offsetX = transEvent.offsetX + transEvent.startX - originPiont.x;
  const offsetY = transEvent.offsetY + transEvent.startY - originPiont.y;

  switch (transType) {
    case "move":
      offset.x += transEvent.offsetX * 2;
      offset.y += transEvent.offsetY * 2;
      break;
    case "rotate":
      if (offsetY > 0) {
        offset.r = (Math.atan(-offsetX / offsetY) * 180) / Math.PI;
      } else if (offsetX < 0) {
        offset.r = (Math.atan(offsetY / offsetX) * 180) / Math.PI + 90;
      } else {
        offset.r = (Math.atan(offsetY / offsetX) * 180) / Math.PI - 90;
      }
      break;
    case "scale":
      offset.s = +(
        offset.s *
        (1 + (transEvent.offsetX * 2) / transEvent.width)
      ).toFixed(2);
  }

  return offset;
}

const transform: TransCreateFn = (transType: string) => ({
  mousemove() {
    const style = this.module.helper.createStyle({
      transform: getTransform.call(this, transType),
      size: [0,0]
    });
    Object.entries(style).forEach(([key, value]: any[]) => {
      this.compEl.style[key] = value;
    });
  },
  mouseup() {
    this.module.actions.setCompTransform(
      this.currComp,
      getTransform.call(this, transType)
    );
  },
});

export const move = transform.bind(null, "move");
export const rotate = transform.bind(null, "rotate");
export const scale = transform.bind(null, "scale");
