import './Selector.scss';
import * as React from 'react';
import { IContainerModel } from '../../../../Interfaces/IContainerModel';
import { SHOW_SELECTOR_TEXT } from '../../../../utils/default';
import { GetAbsolutePosition } from '../../../../utils/itertools';
import { RemoveMargin } from '../../../../utils/svg';

interface ISelectorProps {
  containers: Map<string, IContainerModel>
  selected?: IContainerModel
  scale?: number
}

export function Selector(props: ISelectorProps): JSX.Element {
  if (props.selected === undefined || props.selected === null) {
    return (
      <rect visibility={'hidden'}>
      </rect>
    );
  }

  const scale = (props.scale ?? 1);
  let [x, y] = GetAbsolutePosition(props.containers, props.selected);
  let [width, height] = [
    props.selected.properties.width,
    props.selected.properties.height
  ];

  ({ x, y, width, height } = RemoveMargin(x, y, width, height,
    props.selected.properties.margin.left,
    props.selected.properties.margin.bottom,
    props.selected.properties.margin.top,
    props.selected.properties.margin.right
  ));

  const xText = x + width / 2;
  const yText = y + height / 2;

  const style: React.CSSProperties = {
    stroke: '#3B82F6',
    strokeWidth: 4 / scale,
    fillOpacity: 0,
    transitionProperty: 'all',
    transitionTimingFunction: 'cubic-bezier(0.4, 0, 0.2, 1)',
    transitionDuration: '150ms',
    animation: 'fadein 750ms ease-in alternate infinite'
  };

  return (
    <>
      <rect
        x={x}
        y={y}
        width={width}
        height={height}
        style={style}
      >
      </rect>
      {SHOW_SELECTOR_TEXT
        ? <text
          x={xText}
          y={yText}
          style={{
            transform: `scale(${1 / scale}) translateX(-50%)`,
            transformBox: 'fill-box'
          }}
        >
          {props.selected.properties.displayedText}
        </text>
        : null}
    </>
  );
}
