import { createSelector } from 'reselect';
import isEmpty from 'lodash/isEmpty';
import groupBy from 'lodash/groupBy';
import qs from 'query-string';
import { lowerUpperFirst } from 'utils';

const getIso = state => state.iso || null;
const getAdaptations = state => state.adaptations || null;
const getSearch = state => state.search || null;
const getCountries = state => state.countriesData || null;

const getSection = (sections, slug) => sections.find(s => s.slug === slug);

const getDataFromIso = (sections, iso, slug) => {
  const section = getSection(sections, slug);
  if (section && section.values) {
    const isoValue = section.values.find(country => country.location === iso);
    return isoValue ? [{ ...isoValue, id: iso }] : [{ id: iso }];
  }
  return null;
};

const getDataFromQuery = (sections, isos, countries, slug) => {
  const section = getSection(sections, slug);
  return (
    section &&
    section.values &&
    isos.map(iso => {
      if (iso) {
        const isoValues = section.values.find(
          country => country.location === iso
        );
        const countryLabel = countries.find(
          country => country.iso_code3 === iso
        );
        return isoValues
          ? { ...isoValues, id: iso, label: countryLabel.wri_standard_name }
          : {
            location: iso,
            value: null,
            id: iso,
            label: countryLabel.wri_standard_name
          };
      }
      return { location: null, value: null, id: Math.random() };
    })
  );
};

const getData = (sections, iso, isos, countries, slug) => {
  if (!isos) {
    return getDataFromIso(sections, iso, slug);
  }
  return getDataFromQuery(sections, isos, countries, slug);
};

const getListDataFromIso = (sections, iso, slug) => {
  const items = sections.filter(section => section.slug.startsWith(slug));
  const itemList = [];
  if (
    !items.some(item => item.values.some(country => country.location === iso))
  ) {
    itemList.push('No data');
  } else {
    items.forEach(item => {
      const countryHasItem = item.values.find(
        country => country.location === iso && country.value === true
      );
      if (countryHasItem) itemList.push({ name: item.name });
    });
  }
  return itemList;
};

const getListDataFromQuery = (sections, isos, slug) => {
  const items = sections.filter(section => section.slug.startsWith(slug));
  const itemList = [];
  isos.forEach((iso, index) => {
    if (
      isos.length === 1 &&
      !items.some(item => item.values.some(country => country.location === iso))
    ) {
      itemList.push('No data');
    } else {
      items.forEach(item => {
        const countryHasItem = item.values.find(
          country => country.location === iso && country.value === true
        );
        if (countryHasItem) {
          itemList.push({ name: item.name, countryIndex: [index] });
        }
      });
    }
  });
  if (itemList[0] !== 'No data') {
    const groupedList = groupBy(itemList, 'name');
    const reducedList = Object.keys(groupedList).reduce(
      (array, key) =>
        array.concat({
          name: key,
          countryIndex: groupedList[key].map(x => x.countryIndex)
        }),
      []
    );
    return reducedList;
  }
  return itemList;
};

const getListData = (sections, iso, isos, slug) => {
  if (!isos) {
    return getListDataFromIso(sections, iso, slug);
  }
  return getListDataFromQuery(sections, isos, slug);
};

const getListMetadata = (sections, iso, slug) => {
  const section = getSection(sections, slug);
  const locationUrl = section.values.find(country => country.location === iso);
  return locationUrl && locationUrl.value;
};

export const getQueryIsos = search => {
  if (!search) return null;
  const query = qs.parse(search);
  if (!query.locations) return null;
  return query.locations.split(',').map(val => {
    if (val) return val;
    return null;
  });
};

export const getSectionData = createSelector(
  [getIso, getAdaptations, getSearch, getCountries],
  (iso, adaptations, search, countries) => {
    const queryIsos = getQueryIsos(search);
    const sections = adaptations.data;
    if ((!iso || isEmpty(sections)) && (!search || isEmpty(sections))) {
      return null;
    } // eslint-disable-line no-mixed-operators

    return [
      {
        sectionType: 'CIRCULAR',
        title: getSection(sections, 'poverty_14').name,
        slug: 'poverty_14',
        data: getData(sections, iso, queryIsos, countries, 'poverty_14')
      },
      {
        sectionType: 'LIST',
        title: 'Key hazards',
        slug: 'key_hazard',
        data: getListData(sections, iso, queryIsos, 'hazard'),
        metadataUrl: getListMetadata(sections, iso, 'wb_urls')
      },
      {
        sectionType: 'LINE',
        title: lowerUpperFirst(getSection(sections, 'climate_risks').name),
        subtitle: 'Lower score indicates high levels of climate risk',
        slug: 'climate_risks',
        data: getData(sections, iso, queryIsos, countries, 'climate_risks'),
        maximum: getSection(sections, 'climate_risks').maximum
      },
      {
        sectionType: 'LINE',
        title: getSection(sections, 'vulnerability').name,
        subtitle: 'Lower score indicates less vulnerability',
        slug: 'vulnerability',
        data: getData(sections, iso, queryIsos, countries, 'vulnerability'),
        maximum: getSection(sections, 'vulnerability').maximum
      },
      {
        sectionType: 'LINE',
        title: getSection(sections, 'readiness').name,
        subtitle: 'Higher score indicates high levels of readiness',
        slug: 'readiness',
        data: getData(sections, iso, queryIsos, countries, 'readiness'),
        maximum: getSection(sections, 'readiness').maximum
      },
      {
        sectionType: 'LINK',
        slug: 'link'
      }
    ];
  }
);

export default {
  getSectionData
};

@@ -4129,51 +4129,103 @@
     
-if ((!iso %7C%7C isEmpty(sections)) && (!search
+const noCountriesSelected = !iso && !search;%0A%0A    if (noCountriesSelected %7C%7C isEmpty(countries)
  %7C%7C 
@@ -4242,17 +4242,16 @@
 ctions))
-)
  %7B%0A     

Fix country compare page crash on wri country labels