import ChangeLogModal from "./change-log-modal";
const url = `${process.env.REACT_APP_FUDS_CHANGE_LOG_URL}`;

export default {
  name: "changeLog",

  getReducer: () => {
    const initialData = {
      items: [],
      allItems: [],
      renderModal: false,
      districtFilter: { label: "All Districts", value: "All" },
      searchBarFilter: "",
      executeSearch: false,
    };

    return (state = initialData, { type, payload }) => {
      switch (type) {
        case "CHANGE_LOG_LOAD_ALL_DATA":
        case "CHANGE_LOG_MODAL_WINDOW_OPENED":
        case "CHANGE_LOG_LOAD_SELECTED_DATA":
        case "CHANGE_LOG_SET_DISTRICT_FILTER":
        case "CHANGE_LOG_SET_SEARCH_BAR_FILTER":
        case "CHANGE_LOG_EXECUTE_SEARCH":
          return Object.assign({}, state, payload);
        default:
          return state;
      }
    };
  },

  doSearchChangeLogData:
    () =>
    ({ dispatch, store }) => {
      dispatch({
        type: "CHANGE_LOG_EXECUTE_SEARCH",
        payload: { executeSearch: false },
      });

      let logData = store.selectAllChangeLogItems();
      let districtFilter = store.selectDistrictFilter();
      let targetValue = store.selectSearchBarFilter().trim().toUpperCase();
      let filteredChangeLogData = [];

      if (districtFilter.value !== "All") {
        filteredChangeLogData = logData.filter(
          (log) => log.district_code === districtFilter.value
        );
      } else {
        filteredChangeLogData = logData;
      }

      if (targetValue.length > 0) {
        const wkLogData = [];
        filteredChangeLogData.forEach((item) => {
          let wkKey = {};
          let displayRecord = null;

          for (const [key, value] of Object.entries(item)) {
            if (typeof value == "string") {
              let newObj = value.trim().toUpperCase().includes(targetValue)
                ? item
                : false;
              if (newObj) {
                displayRecord = true;
              }
            }
          }
          if (displayRecord) {
            wkLogData.push(item);
          }
        });

        console.log("SELECTED ITEMS");
        console.log(wkLogData);
        dispatch({
          type: "CHANGE_LOG_LOAD_SELECTED_DATA",
          payload: { items: wkLogData },
        });
      } else {
        dispatch({
          type: "CHANGE_LOG_LOAD_SELECTED_DATA",
          payload: { items: filteredChangeLogData },
        });
      }
    },

  doGetChangeLogData:
    () =>
    ({ dispatch, store, anonGet }) => {
      anonGet(url, (err, response, body) => {
        if (err || response.statusCode !== 200) {
        } else {
          try {
            console.log("Production Change Log Data");
            console.log(body);
            let data = JSON.parse(body);
            console.log("data");
            console.log(data);
            let items = data.items;
            console.log("ITEMS");
            console.log(items);
            dispatch({
              type: "CHANGE_LOG_LOAD_ALL_DATA",
              payload: { allItems: items, renderModal: false },
            });
            dispatch({
              type: "CHANGE_LOG_LOAD_SELECTED_DATA",
              payload: { items: items, renderModal: true },
            });
          } catch (err) {
            // alert(" ! ! ! ERROR IN CATCH BLOCK ! ! ! ")
          }
        }
      });
    },

  doOpenModalLog:
    () =>
    ({ dispatch, store }) => {
      store.doModalOpen({
        children: [ChangeLogModal],
        options: {},
        openedBy: "ChangeLogButton",
      });

      dispatch({
        type: "CHANGE_LOG_MODAL_WINDOW_OPENED",
        payload: { renderModal: false },
      });
    },

  doSetDistrictFilter:
    (opts) =>
    ({ dispatch }) => {
      dispatch({
        type: "CHANGE_LOG_SET_DISTRICT_FILTER",
        payload: { districtFilter: opts },
      });
      dispatch({
        type: "CHANGE_LOG_EXECUTE_SEARCH",
        payload: { executeSearch: true },
      });
    },

  doSetSearchBarFilter:
    (text) =>
    ({ dispatch }) => {
      dispatch({
        type: "CHANGE_LOG_SET_SEARCH_BAR_FILTER",
        payload: { searchBarFilter: text },
      });
      dispatch({
        type: "CHANGE_LOG_EXECUTE_SEARCH",
        payload: { executeSearch: true },
      });
    },

  selectChangeLogItems: (state) => {
    return state.changeLog.items;
  },

  selectAllChangeLogItems: (state) => {
    return state.changeLog.allItems;
  },

  selectDistrictFilter: (state) => {
    return state.changeLog.districtFilter;
  },
  selectSearchBarFilter: (state) => {
    return state.changeLog.searchBarFilter;
  },
  reactRenderChangeLogModal: (state) => {
    if (state.changeLog.renderModal) return { actionCreator: "doOpenModalLog" };
  },
  reactDoSearchChangeLogData: (state) => {
    if (state.changeLog.executeSearch)
      return { actionCreator: "doSearchChangeLogData" };
  },
};
