import styled from "@emotion/styled";
import { inject, observer } from "mobx-react";
import React, { useRef } from "react";
import { LIGHT_TERTIARY_ONE } from "../../../shared/colors";
import { SlideRectangle } from "../../../shared/types";
import { generateRandomColor } from "../../../shared/utils/utils";
import { StoreProps } from "../../platform/SlideshowStore";
import withPlatform, { PlatformProps } from "../../platform/withPlatform";
import Resizer from "./Resizer";
import { CurrentScreen, getCanvasPosition } from "./windowListeners";

type Props = {
  slideRectangle: SlideRectangle;
} & PlatformProps &
  StoreProps;

function SlideObjectRectangle(props: Props) {
  const rectangleRef = useRef<HTMLDivElement>(null);
  const userOfSelectedElement = props.store.subscriberSelectedElements.get(
    props.slideRectangle.id
  );

  return (
    <Resizer
      elementId={props.slideRectangle.id}
      top={props.slideRectangle.y}
      left={props.slideRectangle.x}
      width={props.slideRectangle.width}
      height={props.slideRectangle.height}
      visible={
        props.store.selectedSlideElement.get() === props.slideRectangle.id
      }
      store={props.store}
    >
      <div
        ref={rectangleRef}
        style={{
          position: "relative",
          cursor: "default",
          width: "100%",
          height: "100%",
          backgroundColor: LIGHT_TERTIARY_ONE,
          ...(userOfSelectedElement &&
            userOfSelectedElement !== props.store.userId.get() && {
              border: `2px solid ${generateRandomColor(userOfSelectedElement)}`,
            }),
        }}
        onClick={(e) => {
          props.store.setSelectedSlideElement(props.slideRectangle.id);
          e.stopPropagation();
        }}
        onMouseDown={(e) => {
          if (
            props.store.selectedSlideElement.get() === props.slideRectangle.id
          ) {
            const canvasPosition = getCanvasPosition(e, props.store);
            CurrentScreen.canvasX = canvasPosition.x;
            CurrentScreen.canvasY = canvasPosition.y;
            CurrentScreen.screenX = e.screenX;
            CurrentScreen.screenY = e.screenY;
            props.store.currentDragElement.set(props.slideRectangle.id);
          }
        }}
        onMouseMove={(e) => {}}
        onMouseUp={(e) => {}}
      />
    </Resizer>
  );
}

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

const Container = styled.div``;
