import { createSelector, createStructuredSelector } from 'reselect';
import isEmpty from 'lodash/isEmpty';
import startCase from 'lodash/startCase';
import flatten from 'lodash/flatten';

import { getActiveDatasetsState } from 'components/map-v2/selectors';

import { getVisibility } from 'components/map-v2/components/recent-imagery/recent-imagery-selectors';
import { initialState } from './menu-reducers';
import {
  datasetsSections,
  searchSections,
  mobileSections
} from './menu-sections';

const getMenuUrlState = state =>
  (state.location.query && state.location.query.menu) || null;
const getCountries = state => state.countryData.countries || null;
const getLoading = state =>
  state.datasets.loading || state.countryData.loading || null;
const getDatasets = state => state.datasets.datasets || null;
const getLocation = state => state.location && state.location.payload;

// setting from state
export const getMenuSettings = createSelector([getMenuUrlState], urlState => ({
  ...initialState,
  ...urlState
}));

export const getMenuSection = createSelector(
  [getMenuSettings],
  settings => settings.menuSection
);

export const getSelectedCountries = createSelector(
  [getMenuSettings],
  settings => settings.selectedCountries
);

export const getDatasetCategory = createSelector(
  [getMenuSettings],
  settings => settings.datasetCategory
);

export const getSearch = createSelector(
  [getMenuSettings],
  settings => settings.search
);

export const getSearchType = createSelector(
  [getMenuSettings],
  settings => settings.searchType
);

export const getExploreType = createSelector(
  [getMenuSettings],
  settings => settings.exploreType
);

// get countries by datasets
export const getAvailableCountries = createSelector(
  [getCountries, getDatasets],
  (countries, datasets) => {
    if (isEmpty(countries) || isEmpty(datasets)) return null;
    const validIsos = flatten(datasets.filter(d => !d.global).map(d => d.iso));
    return countries.filter(c => validIsos.includes(c.value));
  }
);

export const getUnselectedCountries = createSelector(
  [getAvailableCountries, getSelectedCountries],
  (countries, selectedCountries) => {
    if (!countries) return null;
    return countries.filter(c => !selectedCountries.includes(c.value));
  }
);

export const getActiveCountries = createSelector(
  [getCountries, getSelectedCountries],
  (countries, selectedCountries) => {
    if (!countries) return null;
    return countries.filter(c => selectedCountries.includes(c.value));
  }
);

// build datasets with available countries data
export const getDatasetSections = createSelector(
  [getDatasets, getActiveCountries],
  (datasets, countries) => {
    if (isEmpty(datasets)) return datasetsSections;

    return datasetsSections.map(s => {
      const { category, subCategories } = s;
      const sectionDatasets =
        datasets && datasets.filter(d => d.tags.includes(category));
      let subCategoriesWithDatasets = [];
      if (subCategories) {
        subCategoriesWithDatasets = subCategories.map(subCat => ({
          ...subCat,
          datasets:
            sectionDatasets &&
            sectionDatasets.filter(
              d => d.tags.includes(subCat.slug) && d.global
            )
        }));
      }
      let countriesWithDatasets = [];
      if (countries) {
        countriesWithDatasets = countries.map(c => ({
          title: c.label,
          slug: c.value,
          datasets:
            sectionDatasets &&
            sectionDatasets.filter(d => !d.global && d.iso.includes(c.value))
        }));
      }

      return {
        ...s,
        datasets: sectionDatasets,
        subCategories: countriesWithDatasets.concat(subCategoriesWithDatasets)
      };
    });
  }
);

export const getDatasetSectionsWithData = createSelector(
  [getDatasetSections, getActiveDatasetsState, getDatasetCategory],
  (sections, activeDatasets, datasetCategory) => {
    if (!activeDatasets) return sections;
    const datasetIds = activeDatasets.map(d => d.dataset);

    return sections.map(s => {
      const { datasets, subCategories } = s;
      return {
        ...s,
        active: datasetCategory === s.category,
        layerCount:
          datasets &&
          datasets.filter(d => activeDatasets && datasetIds.includes(d.id))
            .length,
        datasets:
          datasets &&
          datasets.map(d => ({
            ...d,
            active: datasetIds.includes(d.id)
          })),
        subCategories:
          subCategories &&
          subCategories.map(subCat => ({
            ...subCat,
            datasets:
              subCat.datasets &&
              subCat.datasets.map(d => ({
                ...d,
                active: datasetIds.includes(d.id)
              }))
          }))
      };
    });
  }
);

export const getAllSections = createSelector(
  [getDatasetSectionsWithData],
  datasetSections => {
    if (!datasetSections) return null;

    return datasetSections.concat(searchSections).concat(mobileSections);
  }
);

export const getActiveSection = createSelector(
  [getAllSections, getMenuSection, getDatasetCategory],
  (sections, menuSection, datasetCategory) => {
    if (!sections || !menuSection) return null;

    return sections.find(
      s =>
        (s.category
          ? s.category === datasetCategory && s.slug === menuSection
          : s.slug === menuSection)
    );
  }
);

export const getActiveSectionWithData = createSelector(
  [getActiveSection],
  section => {
    if (!section) return null;
    const subCatsWithData =
      section.subCategories &&
      section.subCategories.filter(s => !isEmpty(s.datasets));

    return {
      ...section,
      ...(!isEmpty(subCatsWithData) && {
        subCategories: subCatsWithData
      })
    };
  }
);

export const getZeroDataCountries = createSelector(
  [getActiveSection],
  section => {
    if (!section) return null;
    const noDataCountries =
      section.subCategories &&
      section.subCategories.filter(s => isEmpty(s.datasets));
    return noDataCountries ? noDataCountries.map(s => s.title) : null;
  }
);

export const getSearchSections = createSelector([getMenuSection], menuSection =>
  searchSections.map(s => ({
    ...s,
    active: menuSection === s.slug
  }))
);

export const getMobileSections = createSelector(
  [getMenuSection, getActiveDatasetsState, getLocation],
  (menuSection, activeDatasets, location) =>
    mobileSections.map(s => ({
      ...s,
      ...(s.slug === 'datasets' && {
        layerCount: activeDatasets && activeDatasets.length
      }),
      ...(s.slug === 'analysis' && {
        highlight: location && !!location.type && !!location.adm0
      }),
      active: menuSection === s.slug
    }))
);

export const getDatasetCategories = createSelector(
  [getDatasetSectionsWithData],
  datasets =>
    datasets &&
    datasets.map(s => ({
      ...s,
      label: startCase(s.category)
    }))
);

export const getMenuProps = createStructuredSelector({
  datasetSections: getDatasetSectionsWithData,
  searchSections: getSearchSections,
  mobileSections: getMobileSections,
  activeSection: getActiveSectionWithData,
  menuSection: getMenuSection,
  countriesWithoutData: getZeroDataCountries,
  countries: getUnselectedCountries,
  selectedCountries: getActiveCountries,
  activeDatasets: getActiveDatasetsState,
  datasetCategory: getDatasetCategory,
  datasetCategories: getDatasetCategories,
  exploreType: getExploreType,
  search: getSearch,
  searchType: getSearchType,
  location: getLocation,
  loading: getLoading,
  recentVisible: getVisibility
});

@@ -3792,32 +3792,37 @@
 ateSelector(%0A  %5B
+%0A    
 getDatasetSectio
@@ -3820,24 +3820,28 @@
 setSections,
+%0A   
  getActiveDa
@@ -3848,24 +3848,28 @@
 tasetsState,
+%0A   
  getDatasetC
@@ -3867,32 +3867,55 @@
 tDatasetCategory
+,%0A    getMenuSection%0A  
 %5D,%0A  (sections, 
@@ -3937,32 +3937,45 @@
  datasetCategory
+, menuSection
 ) =%3E %7B%0A    if (!
@@ -4214,24 +4214,50 @@
 = s.category
+ && menuSection === s.slug
 ,%0A        la

fix selected dataset cat when closed menu