import * as React from 'react';
import { ContainerModel } from '../../../Interfaces/IContainerModel';
import { DIMENSION_MARGIN } from '../../../utils/default';
import { getAbsolutePosition, MakeBFSIterator } from '../../../utils/itertools';
import { transformX } from './Container';
import { Dimension } from './Dimension';

interface IDimensionLayerProps {
  roots: ContainerModel | ContainerModel[] | null
}

const getDimensionsNodes = (root: ContainerModel): React.ReactNode[] => {
  const it = MakeBFSIterator(root);
  const dimensions: React.ReactNode[] = [];
  let currentDepth = 0;
  let min = Infinity;
  let max = -Infinity;
  let lastY = 0;
  for (const { container, depth } of it) {
    if (currentDepth !== depth) {
      AddNewDimension(currentDepth, min, max, lastY, dimensions);

      currentDepth = depth;
      min = Infinity;
      max = -Infinity;
    }

    const absoluteX = getAbsolutePosition(container)[0];
    const x = transformX(absoluteX, container.properties.width, container.properties.XPositionReference);
    lastY = container.properties.y + container.properties.height;
    if (x < min) {
      min = x;
    }

    if (x > max) {
      max = x;
    }
  }

  AddNewDimension(currentDepth, min, max, lastY, dimensions);

  return dimensions;
};

/**
 * A layer containing all dimension
 * @param props
 * @returns
 */
export const DepthDimensionLayer: React.FC<IDimensionLayerProps> = (props: IDimensionLayerProps) => {
  let dimensions: React.ReactNode[] = [];
  if (Array.isArray(props.roots)) {
    props.roots.forEach(child => {
      dimensions.concat(getDimensionsNodes(child));
    });
  } else if (props.roots !== null) {
    dimensions = getDimensionsNodes(props.roots);
  }
  return (
    <g>
      { dimensions }
    </g>
  );
};

function AddNewDimension(currentDepth: number, min: number, max: number, lastY: number, dimensions: React.ReactNode[]): void {
  const id = `dim-depth-${currentDepth}`;
  const xStart = min;
  const xEnd = max;
  const y = lastY + (DIMENSION_MARGIN * (currentDepth + 1));
  const strokeWidth = 1;
  const width = xEnd - xStart;
  const text = width.toString();

  if (width === 0) {
    return;
  }

  dimensions.push(
    <Dimension
      key={id}
      id={id}
      xStart={xStart}
      yStart={y}
      xEnd={xEnd}
      yEnd={y}
      strokeWidth={strokeWidth}
      text={text} />
  );
}
