import { useState, useEffect } from 'react'
import { ChartTimeBase } from './ChartTimeBase'

const chartPluginsOptions = {
  plugins: {
    datalabels: {
      backgroundColor: 'transparent',
      borderRadius: 4,
      color: '#000B',
      display: context => (context.dataset.label === 'wellDepth') && 'auto',
      formatter: value => `${value.y.toLocaleTimeString()} ${value.label.toPrecision(4)}`,
      padding: 6,
      align: 'left',
      anchor: 'center',
      clip: true
    },
    legend: { display: false },
    tooltip: { enable: true }
  }
}

const GetRandomColor = () => '#' + Math.floor(Math.random()*(16**6-1)).toString(16)

export const GetOrCreateDatasetByLineConfig = (data, lineConfig) => {
  let dataset = data?.datasets.find(d => d.label === lineConfig.label)
  if(!dataset) {
    let color = lineConfig.borderColor
      ?? lineConfig.backgroundColor
      ?? lineConfig.color
      ?? GetRandomColor()

    dataset = {
      label: lineConfig.label,
      data: [],
      backgroundColor: lineConfig.backgroundColor ?? color,
      borderColor: lineConfig.borderColor ?? color,
      borderWidth: lineConfig.borderWidth ?? 1,
      borderDash: lineConfig.dash ?? [],
      showLine: lineConfig.showLine ?? !lineConfig.isShape,
      fill: lineConfig.fill ?? (lineConfig.isShape ? 'shape' : 'none')
    }

    data.datasets.push(dataset)
  }
  return dataset
}

export const Column = ({ lineGroup, data, postParsing, interval, yDisplay, yStart, pointCount, savePreviousData }) => {
  const [dataParams, setDataParams] = useState({data: {datasets:[]}, yStart, })

  useEffect(()=>{
    if((lineGroup.length === 0) || (data.length === 0)) return

    setDataParams((preDataParams) => {
      lineGroup.forEach(lineCfg => {
        const dataset = GetOrCreateDatasetByLineConfig(preDataParams.data, lineCfg)
        let points = data.map(dataItem => ({
          x: lineCfg.xConstValue ?? dataItem[lineCfg.xAccessorName],
          label: dataItem[lineCfg.xAccessorName],
          y: new Date(dataItem[lineCfg.yAccessorName]),
          depth: dataItem.wellDepth
        })).filter(point => (point.x ?? null) !== null && (point.y ?? null) !== null)

        if (savePreviousData)
          points = [...dataset.data, ...points]

        if(points?.length > 2)
          points.sort((a,b) => a.y > b.y ? 1 : -1)
        if(points.length > pointCount)
          points.splice(0, points.length - pointCount)

        dataset.data = points
      })

      preDataParams.yStart = yStart
      preDataParams.yInterval = interval
      preDataParams.displayLabels = yDisplay

      postParsing?.(preDataParams)
      return {...preDataParams}
    })

  }, [data, lineGroup, interval, yDisplay, yStart, postParsing, pointCount, savePreviousData])

  return <ChartTimeBase dataParams = { dataParams } options = { chartPluginsOptions } />
}

Column.defaultProps = {
  pointCount: 2048,
  savePreviousData: false
}
