import { useEffect, useState } from 'react'
import { Grid, GridItem } from '../../components/Grid'
import { ArchiveColumn } from './ArchiveColumn'
import { paramsGroups } from '../TelemetryView'

const interpolationSearch = (data, begin, end, accessor) => {
    const fy = (i) => new Date(data[i]?.[accessor] ?? 0)
    const fx = (y, b, e) => Math.round(b + (y - fy(b)) * (e - b) / (fy(e) - fy(b)))
    const findIdx = (val, startIdx, c) => {
        let x = startIdx
        let endIdx = data.length - 1
        if(val < fy(startIdx))
          return startIdx
        if(val > fy(endIdx))
          return endIdx
        for(let i = 0; i < c; i++){
          x = fx(val, startIdx, endIdx)
          if(fy(x) < val)
            startIdx = x
          else
            endIdx = x
          if ((startIdx === endIdx)||(fy(startIdx) === fy(endIdx)))
            return x
        }
        return x
      }
      let x0 = findIdx(begin, 0, 5)
      let x1 = findIdx(end, x0, 3)
      return { start: x0, end: x1, count: x1 - x0 }
}

export const cutData = (data, beginDate, endDate) => {
    if (data?.length > 0) {
        let { start, end } = interpolationSearch(data, beginDate, endDate, 'date')
        if (start > 0) start--
        if (end + 1 < end.length) end++
        return data.slice(start, end)
    }
    return data
}

export const ArchiveDisplay = ({data, startDate, interval, onWheel}) => {
    const [chartData, setChartData] = useState([])

    useEffect(() => {
        const endDate = new Date(+startDate + interval)
        setChartData(cutData(data, startDate, endDate))
    }, [data, startDate, interval])

    return (
        <Grid onWheel={onWheel}>
            {paramsGroups.map((group, index) => (
                <GridItem col={index + 1} row={'1'} className={'border_small'} key={`${group.label}${index}`} style={{ padding: 0 }}>
                    <ArchiveColumn
                        style={{ width: '15vw' }}
                        data={chartData}
                        lineGroup={group}
                        interval={interval}
                        headerHeight={'50px'}
                        yStart={startDate}
                    />
                </GridItem>
            ))}
        </Grid>
    )
}
