import Highcharts from 'highcharts'
import merge from 'lodash.merge'
import enableAccessibilityMode from 'highcharts/modules/accessibility'
import enableDataLoader from 'highcharts/modules/data'
import create from './dom/create'

Highcharts.theme = {
  chart: {
    height: 300,
    style: {
      fontFamily: 'inherit',
      fontSize: '100%',
    },
  },
  colors: [
    'var(--color-blue6)',
    'var(--color-gray6)',
    'var(--color-red6)',
    'var(--color-yellow6)',
    'var(--color-green6)',
  ],
}

enableAccessibilityMode(Highcharts)
enableDataLoader(Highcharts)
Highcharts.setOptions(Highcharts.theme)

export default class Chart {
  constructor(table: HTMLTableElement) {
    const chart = create('div', { className: 'Chart' })
    table.parentNode?.insertBefore(chart, table.nextSibling)
    table.style.display = 'none'

    const options = merge(
      Chart.getDefaults(),
      JSON.parse(table.dataset.options || '{}'),
      {
        data: {
          table: table,
        },
      },
    )

    Highcharts.chart(chart, options)
  }

  static getDefaults() {
    return {
      credits: { enabled: false },
      title: undefined,
    }
  }
}
