import * as React from 'react';
import { ContainerModel, getDepth, MakeIterator } from '../../../Interfaces/ContainerModel';
import { Dimension } from './Dimension';

interface IDimensionLayerProps {
  isHidden: boolean,
  roots: ContainerModel | ContainerModel[] | null,
}

const GAP: number = 50;

const getDimensionsNodes = (root: ContainerModel): React.ReactNode[] => {
  const it = MakeIterator(root);
  const dimensions: React.ReactNode[] = [];
  for (const container of it) {
    // WARN: this might be dangerous later when using other units/rules
    const width = Number(container.properties.width);

    const id = `dim-${container.properties.id}`;
    const xStart: number = container.properties.x;
    const xEnd = xStart + width;
    const y = -(GAP * (getDepth(container) + 1));
    const strokeWidth = 1;
    const text = width.toString();
    dimensions.push(
      <Dimension
        id={id}
        xStart={xStart}
        xEnd={xEnd}
        y={y}
        strokeWidth={strokeWidth}
        text={text}
      />
    );
  }
  return dimensions;
};

/**
 * A layer containing all dimension
 *
 * @deprecated In order to avoid adding complexity
 * with computing the position in a group hierarchy,
 * use Dimension directly inside the Container,
 * Currently it is glitched as
 * it does not take parents into account,
 * and will not work correctly
 * @param props
 * @returns
 */
export const DimensionLayer: 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 visibility={props.isHidden ? 'hidden' : 'visible'}>
      { dimensions }
    </g>
  );
};
