import { trainDataType } from "./trainPositionTextArray";
import { stationIDPair } from "../lib/getStationList";

export const checkDuplicateTrainData = (
  currentTrainArray: trainDataType[],
  stationList: any[]
) => {
  const notSameLineData = checkSameTrain(currentTrainArray, stationList);
  const notNyujoData = notSameLineData.filter((d) => d.delay !== "入線");
  if (currentTrainArray.length == 1) return currentTrainArray[0];
  if (notNyujoData.length == 0) return currentTrainArray[0];
  else return notNyujoData[0];
};

// 二つのデータを比較して、正しい路線を反映しているデータだけを返す関数
const checkSameTrain = (
  currentTrainArray: trainDataType[],
  stationList: any[]
) => {
  const trueLineData = currentTrainArray
    .map((d) => {
      if (d.Pos.match("～")) {
        const [topST, downST] = d.Pos.replace("（下り）", "")
          .replace("（上り）", "")
          .split("～");
        const stopStationList = [topST, downST].map((i) => {
          return stationList.map((a) => a.filter((d) => d.StationName == i));
        });
        const x = stopStationList.map((i, index, array) => {
          if (index == array.length - 1) return;

          const firstItem = array[index];
          const secondItem = array[index + 1];
          let betweenStationLine = "";
          let baseStationNumberFirst = "";
          let baseStationNumberSecond = "";
          Object.keys(stationIDPair).forEach((d, index2, array) => {
            if (!d) return;
            const haveFirst = firstItem[index2];
            const haveSecond = secondItem[index2];
            if (haveFirst.length && haveSecond.length) {
              betweenStationLine = d;
              baseStationNumberFirst = haveFirst[0].StationNumber;
              baseStationNumberSecond = haveSecond[0].StationNumber;
            }
          });

          return betweenStationLine;
        });
        return x;
      } else {
        const ST = d.Pos.replace("（下り）", "").replace("（上り）", "");
        const stopStationList = stationList.map((a) =>
          a.filter((d) => d.StationName == ST)
        );

        const string = Object.keys(stationIDPair).map((d, index2, array) => {
          if (!d) return;
          if (!stopStationList[index2].length) return;
          return d;
        });
        return string;
      }
    })
    .map((x) => x.filter((d) => d != undefined));
  const returnData = currentTrainArray.filter((d, index) => {
    return d.Line == trueLineData[index][0];
  });
  return returnData;
};
