import React, { ReactNode, useState } from 'react';
import Measure from 'react-measure';

interface ISize {
  width: number; 
  height: number;
}

interface ResponsiveWrapperProps {
  children: (size?: ISize) => ReactNode;
}

const ResponsiveWrapper = ({ children }: ResponsiveWrapperProps) => {
  const [ size, setSize ] = useState<ISize | undefined>({
    width: -1,
    height: -1,
  });

  const shouldRender = Number(size?.width) > 0 && Number(size?.height) > 0;

  return (
    <Measure
      bounds
      onResize={(contentRect) => setSize(
        contentRect?.bounds )}
    >
      {
        ((props) => (
          <div className="c-chart__responsive-wrapper" ref={props.measureRef} >
            {shouldRender && children(size)}
          </div>)
        )
      }
    </Measure>
  );
};

export { ResponsiveWrapper };
