import { slice } from '../slices';

const nameSpace = slice.name;

export const dataSelector = (state) => state[nameSpace].data;
export const isLoadingSelector = (state) => state[nameSpace].isLoading;
export const selectedStartTimeSelector = (state) => state[nameSpace].selectedStartTime;
export const selectedItemTimeSelector = (state) => state[nameSpace].selectedItemTime;
export const shouldWrapTagsSelector = (state) => state[nameSpace].shouldWrapTags;
export const searchSelector = (state) => state[nameSpace].search;
export const tagInfoSelector = (state) => state[nameSpace].tagInfo;
export const activeTagsFilterSelector = (state) => state[nameSpace].activeTagsFilter;

// computed with simple cache
// for avoid rerenders
let lastActiveTags = null;
let lastData = null;
let lastResult = null;

export const dataWithTagsFilterSelector = (state) => {
  const activeTagsFilter = activeTagsFilterSelector(state);
  const data = dataSelector(state);

  // Check if inputs have changed
  if (lastResult && lastActiveTags === activeTagsFilter && lastData === data) {
    return lastResult;
  }

  const filteredData = data?.reduce((acc, frame) => {
    const log = frame.log
      .map((log$) => {
        const keywords = log$.keywords.filter((keyword) => activeTagsFilter.includes(keyword.category));
        return keywords.length ? { ...log$, keywords } : null;
      })
      .filter(Boolean);

    if (log.length) {
      acc.push({ ...frame, log });
    }

    return acc;
  }, []);

  // Cache the inputs and result
  lastActiveTags = activeTagsFilter;
  lastData = data;
  lastResult = filteredData;

  return filteredData;
};
