import { createSelector } from 'reselect';
import isEmpty from 'lodash/isEmpty';
import { biomassToCO2, biomassToC } from 'utils/calculations';
import { getColorPalette } from 'utils/data';

// get list data
const getData = state => state.data || null;
const getSettings = state => state.settings || null;
const getIndicator = state => state.indicator || null;
const getColors = state => state.colors || null;

export const chartData = createSelector(
  [getData, getSettings],
  (data, settings) => {
    if (!data || isEmpty(data)) return null;

    const { startYear, endYear } = settings;
    return data
      .filter(d => d.year >= startYear && d.year <= endYear)
      .map(d => ({
        ...d,
        biomassCarbon: biomassToC(d.emissions),
        co2Emissions: biomassToCO2(d.emissions)
      }));
  }
);

export const chartConfig = createSelector(
  [getSettings, getColors],
  (settings, colors) => {
    const colorRange = getColorPalette(colors.ramp, 2);
    const { metric } = settings;
    return {
      xKey: 'year',
      yKeys: {
        areas: {
          [metric]: {
            fill: colorRange[0],
            background: false,
            activeDot: true
          }
        }
      },
      unit: 't',
      tooltip: [
        {
          key: [metric],
          unit: 't'
        }
      ]
    };
  }
);

export const getSentence = createSelector(
  [chartData, getSettings, getIndicator],
  (data, settings, indicator) => {
    if (!data || isEmpty(data) || !indicator) return null;

    const { startYear, endYear, metric, threshold } = settings;
    const totalEmissions = data.map(d => d[metric]).reduce((sum, d) => sum + d);
    const emissionType = metric === 'biomassCarbon' ? 'carbon' : 'CO2';
    let indicatorText = '';
    if (indicator.value === 'mining') {
      indicatorText = ` in ${indicator.label.toLowerCase()} regions`;
    } else if (indicator.value !== 'gadm28') {
      indicatorText = ` in ${indicator.label.toLowerCase()}`;
    }
    return `Between <b>${startYear}</b> and <b>${endYear}</b>, <b>${totalEmissions /
      1000000}</b> million tons of <b>${emissionType}</b> were released into the atmosphere as a result of forest loss${indicatorText} where tree canopy is greater than <b>${threshold}%</b>.`;
  }
);

@@ -36,16 +36,52 @@
 elect';%0A
+import %7B format %7D from 'd3-format';%0A
 import i
@@ -2083,16 +2083,49 @@
 %3E, %3Cb%3E$%7B
+format(%0A      '.3s'%0A    )(%0A      
 totalEmi
@@ -2134,42 +2134,20 @@
 ions
- /
 %0A    
-  1000000%7D%3C/b%3E million tons
+)%7Dt%3C/b%3E
  of 

improve tons format