import { createSelector } from 'reselect';
import isEmpty from 'lodash/isEmpty';

/**
 * Direct selector to the templates state domain
 */
const selectTemplatesDomain = () => (state) => state.get('templates');

/**
 * Other specific selectors
 */


/**
 * Default selector used by Templates
 */

const makeSelectTemplates = () => createSelector(
  selectTemplatesDomain(),
  (substate) => substate && substate.toJS()
);

const templateUserList = () => createSelector(
  makeSelectTemplates(),
  (substate) => substate.userList || [],
);

const makeSelectTemplatesResponse = () => createSelector(
  selectTemplatesDomain(), (templatesState) => templatesState.get('templates')
);
const selectTemplateContent = () => createSelector(
  makeSelectTemplates(), (templates) => {
    const {templateDetails} = templates;
    if (!isEmpty(templateDetails)) {
      const templateBase = templateDetails.versions.base;
      const selectedLanguage = templateBase.selectedLanguages[0];
      return templateBase[selectedLanguage]['template-content'];
    }
    return null;
  }
);

const selectEmailLayout = () => createSelector(makeSelectTemplates(), (templates) => {
  const {selectedEmailLayout, sendingFile} = templates;
  if (!sendingFile) {
    return selectedEmailLayout;
  }
  return null;
});
const uploadSelector = () => createSelector(makeSelectTemplates(), (templates) => templates.sendingFile ? templates.sendingFile : false );

const selectCmsTemplates = () => createSelector(makeSelectTemplates(), (templates) => {
  const {getCmsTemplatesInProgress, cmsTemplates} = templates;
  if (!getCmsTemplatesInProgress) {
    return cmsTemplates;
  }
  return null;
});

const selectCmsTemplatesLoader = () => createSelector(
  makeSelectTemplates(),
  (templates) => templates.getCmsTemplatesInProgress,
);

const selectEdmEditor = () => createSelector(makeSelectTemplates(), (templates) => {
  const {edmTemplate} = templates;
  return edmTemplate || null;
});

const selectBEEEditor = () => createSelector(makeSelectTemplates(), (templates) => {
  const {BEETemplate} = templates;
  return BEETemplate || null;
});

const selectArchiveFilter = () => createSelector(
  makeSelectTemplates(),
  (substate) => substate.archiveFilter || 'active',
);

const selectSelectedTemplateIds = () => createSelector(
  makeSelectTemplates(),
  (substate) => substate.selectedTemplateIds || [],
);

export {
  uploadSelector,
  templateUserList,
  makeSelectTemplates,
  makeSelectTemplatesResponse,
  selectTemplateContent,
  selectEmailLayout,
  selectCmsTemplates,
  selectEdmEditor,
  selectBEEEditor,
  selectCmsTemplatesLoader,
  selectArchiveFilter,
  selectSelectedTemplateIds,
};
