import { inject, observer } from "mobx-react";
import React from "react";
import { LIGHT_SECONDARY_ONE } from "../../../shared/colors";
import { SlideConnection } from "../../../shared/types";
import { StoreProps } from "../../platform/SlideshowStore";
import withPlatform, { PlatformProps } from "../../platform/withPlatform";
import { midPoint, returnPointGivenOrientation } from "./windowListeners";

type Props = {
  slideConnection: SlideConnection;
} & PlatformProps &
  StoreProps;

function midPointArrowhead(
  point: { x: number; y: number },
  orientation: string
) {
  if (orientation === "top") {
    return {
      x: point.x,
      y: point.y - 8,
    };
  } else if (orientation === "left") {
    return {
      x: point.x - 8,
      y: point.y,
    };
  } else if (orientation === "right") {
    return {
      x: point.x + 8,
      y: point.y,
    };
  }

  return {
    x: point.x,
    y: point.y + 8,
  };
}

function Connection(props: Props) {
  const currentSlideId = props.store.currentSlide.get()!;
  const currentSlide = props.store.slides.get(currentSlideId)!;
  const startElement = currentSlide.content[props.slideConnection.startId];
  const endElement = currentSlide.content[props.slideConnection.endId];

  const start = returnPointGivenOrientation(
    startElement,
    props.slideConnection.startOrientation
  );
  const end = returnPointGivenOrientation(
    endElement,
    props.slideConnection.endOrientation
  );

  const startMid = midPoint(start, props.slideConnection.startOrientation);

  const endMid = midPoint(end, props.slideConnection.endOrientation);

  const endArrowhead = midPointArrowhead(
    end,
    props.slideConnection.endOrientation
  );

  return (
    <g
      strokeWidth={2}
      stroke={LIGHT_SECONDARY_ONE}
      fill="none"
      markerEnd="url(#arrowhead)"
      pointerEvents="all"
    >
      <path
        d={`M${start.x},${start.y} C${startMid.x},${startMid.y} ${endMid.x},${endMid.y} ${endArrowhead.x},${endArrowhead.y}`}
        onClick={(e) => {
          props.store.selectedSlideElement.set(props.slideConnection.id);
        }}
      />
    </g>
  );
}

export default withPlatform(inject("store")(observer(Connection)));
