import React, {
  createContext,
  useContext,
  useState,
  useEffect,
  FC,
} from "react";
import {
  lineList,
  getStationList,
  lineList_LineWebID,
} from "@/lib/getStationList";
import { StationProps } from "@/lib/CommonTypes";
type initialStateType = {
  originalStationList: StationProps[][];
  setOriginalStationList: React.Dispatch<React.SetStateAction<StationProps[]>>;
  getStationDataFromName: (id: string) => StationProps[];
  getStationDataFromId: (id: string) => StationProps[];
  getStationDataFromNameBase: (name: string) => any[];
  stationList: any[];
  getInjectJavascriptAddress: (StationNumber: string) => string;
};
const initialState = {
  originalStationList: [[]],
  setOriginalStationList: () => {},
  getStationDataFromName: () => [],
  getStationDataFromId: () => [],
  getStationDataFromNameBase: () => [],
  stationList: [],
  getInjectJavascriptAddress: (StationNumber: string) => "",
};

const StationListContext = createContext<initialStateType>(initialState);
type Props = {
  children: React.ReactNode;
};
export const useStationList = () => {
  return useContext(StationListContext);
};

export const StationListProvider: FC<Props> = ({ children }) => {
  const [originalStationList, setOriginalStationList] = useState<any[]>([]);
  useEffect(() => {
    getStationList().then(setOriginalStationList);
  }, []);
  const getStationDataFromId: (id: string) => any[] = (id) => {
    let returnArray = [];
    Object.keys(originalStationList).forEach((key) => {
      originalStationList[key].forEach((station) => {
        if (station.StationNumber === id) {
          returnArray = [
            ...returnArray,
            ...getStationDataFromName(station.Station_JP),
          ];
        }
      });
    });
    return returnArray;
  };
  const getStationDataFromName: (name: string) => any[] = (name) => {
    const returnArray = [];
    Object.keys(originalStationList).forEach((key) => {
      originalStationList[key].forEach((station) => {
        if (station.Station_JP === name) {
          if (!!station.jslodApi) returnArray.push(station);
        }
      });
    });
    return returnArray;
  };

  const getStationDataFromNameBase: (name: string) => any[] = (name) => {
    const returnArray = [];
    Object.keys(originalStationList).forEach((key) => {
      originalStationList[key].forEach((station) => {
        if (!station.StationNumber) return;
        if (
          typeof station.StationNumber === "string" &&
          station.StationNumber.includes(name)
        ) {
          if (!!station.jslodApi) returnArray.push(station);
        } else if (
          typeof station.Station_JP === "string" &&
          station.Station_JP.includes(name)
        ) {
          if (!!station.jslodApi) returnArray.push(station);
        }
      });
    });
    return returnArray;
  };

  const [stationList, setStationList] = useState<any[][]>([[]]);
  useEffect(() => {
    if (originalStationList.length === 0) return;
    const stationList = lineList.map((d) =>
      originalStationList[d].map((a) => ({
        StationNumber: a.StationNumber,
        StationName: a.Station_JP,
      }))
    );
    setStationList(stationList);
  }, [originalStationList]);

  const getInjectJavascriptAddress = (StationNumber: string) => {
    const bootStationList = [];
    Object.keys(originalStationList).forEach((d) => {
      let findNearStations = false;
      originalStationList[d].forEach((x) => {
        let lineName = lineList_LineWebID[d];
        if (findNearStations) {
          if (x.MyStation) {
            bootStationList.push({ line: lineName, station: x });
            findNearStations = false;
          }
          return;
        }
        if (x.StationNumber == StationNumber) {
          if (!x.MyStation) findNearStations = true;
          else bootStationList.push({ line: lineName, station: x });
        }
      });
      if (StationNumber == "M12") {
        bootStationList.push({
          line: "seto",
          station: { Station_JP: "児島", MyStation: "0" },
        });
      }
    });
    console.log(bootStationList[0]);
    if (bootStationList[0] === undefined) return "";
    return `MoveDisplayStation('${bootStationList[0].line}_${bootStationList[0].station.MyStation}_${bootStationList[0].station.Station_JP}');document.getElementById("disp").insertAdjacentHTML("afterbegin", "<div />");setReload();`;
  };

  return (
    <StationListContext.Provider
      value={{
        originalStationList,
        setOriginalStationList,
        getStationDataFromName,
        getStationDataFromId,
        getStationDataFromNameBase,
        stationList,
        getInjectJavascriptAddress,
      }}
    >
      {children}
    </StationListContext.Provider>
  );
};
