import ResourcesModal from './resources-modal';
import { createResourceGroup } from '../../openlayers-utils/resource-utilities';

const url = `${process.env.REACT_APP_FUDS_RESOURCES_URL}`;
const defaultHtml = [
    {"name": "FUDSMIS Portal - Default", "url": "https://fudsportal.usace.army.mil/"},
    {"name": "IPaC Information for Planning and Consultation - Default", "url": "https://ipac.ecosphere.fws.gov/"},
];

export default {
  name: 'resources',
  
  getReducer: () => {
    const initialData = {
      items: defaultHtml,
      groups: {},
      renderModal: false,
    };

    return (state = initialData, { type, payload }) => {
      switch (type) {
        case "RESOURCES_LOAD_TEST_DATA":
        case "RESOURCES_LOAD_PRODUCTION_DATA":
        case "RESOURCES_MODAL_WINDOW_OPENED":
          return Object.assign({}, state, payload);
        default:
          return state;
      }
    };
  },

  doGetResourceData: () => ({dispatch, store, anonGet}) => {
    anonGet(url, (err, response, body) => {
      if (err || response.statusCode !== 200) {
        // On Error Load Test Data
        dispatch({
          type: "RESOURCES_LOAD_TEST_DATA",
          payload: { items: defaultHtml, groups: {}, renderModal: true },
        });

      } else {
      try {
           console.log("Production Resource Data")
           console.log(body)
           let data = JSON.parse(body);
           console.log('data')
           console.log(data)
           

           let items = data.items
           let groups = {};
           groups = createResourceGroup(items);
         
           console.log("ITEMS");
           console.log(items)
           console.log(groups)
          // debugger
           dispatch({
            type: "RESOURCES_LOAD_PRODUCTION_DATA",
            payload: { groups: groups, items: items, renderModal: true },
          });

        } catch (err) {
          // alert(" ! ! ! ERROR IN CATCH BLOCK ! ! ! ")
        }
      }
    });  
  },

  doOpenModalResources: () => ({dispatch, store}) => {
    store.doModalOpen({
      children: [ ResourcesModal ],
      options: {}, 
      openedBy: 'ResourcesButton'
    });
     
      
    dispatch({
      type: "RESOURCES_MODAL_WINDOW_OPENED",
      payload: { renderModal: false },
    });

  },

  selectResourceItems: (state) => {
    return state.resources.items;
  },

  selectResourceGroups: (state) => {
    return state.resources.groups;
  },

  reactRenderResourceModal: (state) => {
    if (state.resources.renderModal === true)
      return { actionCreator: "doOpenModalResources" };
  },

}

