import { LineTimeSerie, LineOptions, LinePod } from '@chartwerk/line-pod';
import { MarkersConf } from '@chartwerk/line-pod/dist/models/marker';
import { SegmentSerie } from '@chartwerk/line-pod/dist/models/segment';

import React, { useEffect, useRef, useState } from 'react';

import _ from 'lodash';


export type ChartwerkLinePodProps = {
  id?: string;
  series: LineTimeSerie[];
  options?: LineOptions;
  markersConf?: MarkersConf,
  segments?: SegmentSerie[],
  className?: string;
}

export function ChartwerkLinePod(props: ChartwerkLinePodProps) {

  const [pod, setPod] = useState<LinePod | null>(null);
  const [hack, setHack] = useState<number | null>(null);

  const chartRef = useRef(null);
  const chart = chartRef.current;

  useEffect(() => {
    // this function will be called on component unmount
    return () => {
      if(pod === null) { return; }
      // @ts-ignore
      pod.removeEventListeners();
    }
  }, []);

  useEffect(() => {
    if(chart === null) { return; }
    if(pod === null) {
      const newPod = new LinePod(
        // @ts-ignore
        chart,
        props.series,
        props.options,
        props.markersConf,
        props.segments
      );
      setPod(newPod);
      newPod.render();
    } else {
      if(props.markersConf) {
        pod.updateMarkers(props.markersConf);
      }
      if(props.segments) {
        pod.updateSegments(props.segments);
      }
      // TODO: actually it's wrong logic with updates
      // because it creates new pod anyway
      pod.updateData(props.series, props.options);
    }
  }, [chart, props.id, props.options, props.markersConf, props.segments]);

  // TODO: it's a hack to render the LinePod right after the div appears in DOM
  setTimeout(() => {
    if(hack === null) {
      setHack(1);
    }
  }, 1);

  return (
    <div id={props.id} className={props.className} ref={chartRef}></div>
  );
}

export default ChartwerkLinePod;
