import React, { memo } from 'react'
import array from 'lodash/array'
import { Line } from 'react-chartjs-2'
import { getRandomColor } from '../utils'

const ServiceProductChart = ({atasks}) => {

  let tasks = [...atasks]
  const monthNames = ["January", "February", "March", "April", "May", "June",
    "July", "August", "September", "October", "November", "December"
  ];
  const labels = []
  const prods = []
  const data = []
  const datasets = []

  array.reverse(tasks)

  tasks.forEach((t) => {
    const d = new Date(t.created_at)
    const dstr = d.getDate() + ' ' + monthNames[d.getMonth()] + ' ' + d.getFullYear()
    labels.push(dstr)
    if (t.custom_fields[2].display_value !== null && prods.indexOf(t.custom_fields[2].display_value) === -1) {
      prods.push(t.custom_fields[2].display_value)
    } else if (t.custom_fields[3].display_value !== null && prods.indexOf(t.custom_fields[3].display_value) === -1) {
      prods.push(t.custom_fields[3].display_value)
    }
  })

  prods.forEach(() => data.push([]))

  if (prods.length > 0) {
    tasks.forEach((t) => {
      prods.forEach((p, idx) => {
        if (t.custom_fields[2].display_value === p || t.custom_fields[3].display_value === p) {
          data[idx].push(1)
        } else {
          data[idx].push(0)
        }
      })
    })
  }
  
  prods.forEach((p, idx) => {
    datasets.push({
      label: p,
      data: data[idx],
      borderColor: getRandomColor(),
    })
  })

  return <Line
    data={{
      labels,
      datasets,
    }}
    options={{
      maintainAspectRatio: false,
      scales: {
        yAxis: {
          min: 0
        },
      },
    }}
  />

}

export default ServiceProductChart