import React, { useState, useCallback, useEffect, useContext } from "react";
import { LogHeaderCharacter } from "../lib/rpdata/logs";
import LogListContext from "./LogListContext";

export interface LogFilterChoiceContextData {
  characters: LogHeaderCharacter[]
  channelNames: string[]
  eventNames: string[]
}

const LogFilterChoiceContext: React.Context<LogFilterChoiceContextData> = React.createContext({
  characters: [],
  channelNames: [],
  eventNames: [],
});

interface LogFilterChoiceContextProviderProps {
  children: JSX.Element | JSX.Element[]
}

export function LogFilterChoiceContextProvider(props: LogFilterChoiceContextProviderProps) {
  const {headers} = useContext(LogListContext);
  const [value, setValue] = useState<LogFilterChoiceContextData>({
    characters: [],
    channelNames: [],
    eventNames: [],
  });

  useEffect(() => {
    const characters = new Map<string, LogHeaderCharacter>();
    const channelNames = new Set<string>();
    const eventNames = new Set<string>();

    for (const header of headers) {
      for (const character of header.characters) {
        characters.set(character.id, character);
      }

      channelNames.add(header.channelName);
      if (header.eventName) {
        eventNames.add(header.eventName);
      }
    }

    setValue(c => c.characters.length < characters.size ? {
      channelNames: Array.from(channelNames.values()),
      eventNames: Array.from(eventNames.values()),
      characters: Array.from(characters.values()),
    } : c);
  }, [headers])

  return (
    <LogFilterChoiceContext.Provider value={value}>
      {props.children}
    </LogFilterChoiceContext.Provider>
  );
}

export default LogFilterChoiceContext