import React from "react";
import { Platform, LayoutAnimation } from "react-native";
import { WebView } from "react-native-webview";

import {
  lineList,
  lineList_LineWebID,
  lineListPair,
  stationIDPair,
  stationNamePair,
} from "../../lib/getStationList";
import { checkDuplicateTrainData } from "../../lib/checkDuplicateTrainData";
import { useFavoriteStation } from "../../stateBox/useFavoriteStation";
import { useCurrentTrain } from "../../stateBox/useCurrentTrain";
import { useDeviceOrientationChange } from "../../stateBox/useDeviceOrientationChange";
import { SheetManager } from "react-native-actions-sheet";

import { useNavigation } from "@react-navigation/native";
import { useTrainMenu } from "../../stateBox/useTrainMenu";
import { useStationList } from "../../stateBox/useStationList";
export const AppsWebView = ({ openStationACFromEachTrainInfo }) => {
  const { webview, currentTrain } = useCurrentTrain();
  const { navigate } = useNavigation();
  const { favoriteStation } = useFavoriteStation();
  const { isLandscape } = useDeviceOrientationChange();
  const { originalStationList, stationList, getInjectJavascriptAddress } =
    useStationList();
  const {
    setSelectedLine,
    mapsStationData: stationData,
    setLoadError,
    setTrainInfo,
    injectJavascript,
  } = useTrainMenu();
  var urlcache = "";
  let once = false;

  const onNavigationStateChange = ({ url }) => {
    if (url == urlcache) return;
    //URL二重判定回避
    urlcache = url;
    switch (true) {
      case url.includes("https://train.jr-shikoku.co.jp/usage.htm"):
        if (Platform.OS === "android") navigate("howto", { info: url });
        webview?.current.goBack();
        //Actions.howto();
        break;
      case url.includes("https://train.jr-shikoku.co.jp/train.html"):
        //Actions.trainbase({info: url});
        if (Platform.OS === "android") navigate("trainbase", { info: url });
        webview?.current.goBack();
        break;
    }
  };
  const onMessage = (event) => {
    const { data } = event.nativeEvent;
    /**
     * {type,trainNum,limited}
     * {type,currentLines}
     * {type,event,id,name,pdf,map,url,chk}
     */
    if (data.includes("train.html")) {
      navigate("trainbase", { info: data, from: "Train" });
      return;
    }
    if (!originalStationList) {
      alert("駅名標データを取得中...");
      return;
    }
    const dataSet = JSON.parse(data);
    switch (dataSet.type) {
      case "LoadError": {
        setLoadError(true);
        return;
      }
      case "PopUpMenu":
        {
          const findStationEachLine = (selectLine) =>
            selectLine.filter((d) => d.StationTimeTable == dataSet.pdf);
          let returnDataBase = lineList
            .map((d) => findStationEachLine(originalStationList[d]))
            .filter((d) => d.length > 0)
            .reduce((pre, current) => {
              pre.push(...current);
              return pre;
            }, []);

          if (returnDataBase.length) {
            const payload = {
              currentStation: returnDataBase,
              navigate: navigate,
              goTo: "Apps",
              useShow: () =>
                SheetManager.show("StationDetailView", { payload }),
              onExit: () => SheetManager.hide("StationDetailView"),
            };
            SheetManager.show("StationDetailView", { payload });
          }
        }
        return;
      case "ShowTrainTimeInfo": {
        const { trainNum, limited } = dataSet;
        //alert(trainNum, limited);
        LayoutAnimation.easeInEaseOut();
        setTrainInfo({
          trainNum,
          limited,
          trainData: checkDuplicateTrainData(
            currentTrain.filter((a) => a.num == trainNum),
            stationList
          ),
        }); //遅延情報は未実装
        if (isLandscape) return;
        const payload = {
          data: { trainNum, limited },
          navigate,
          openStationACFromEachTrainInfo,
        };
        SheetManager.show("EachTrainInfo", { payload });
        return;
      }
      case "currentLines": {
        const lineInfo = dataSet.currentLines.split("\n")[0];
        const lineID = stationNamePair[lineInfo];

        setSelectedLine(lineID);
        return;
      }
      default: {
        return;
      }
    }
  };

  const onLoadEnd = () => {
    if (once) return () => {};
    if (!stationData) return () => {};
    if (!originalStationList) return () => {};
    if (favoriteStation.length < 1) return () => {};
    const string = getInjectJavascriptAddress(
      favoriteStation[0][0].StationNumber
    );
    if (!string) return () => {};
    webview?.current.injectJavaScript(string);
    once = true;
  };

  return (
    <WebView
      useWebKit
      ref={webview}
      source={{ uri: "https://train.jr-shikoku.co.jp/sp.html" }}
      originWhitelist={[
        "https://train.jr-shikoku.co.jp",
        "https://train.jr-shikoku.co.jp/sp.html",
      ]}
      mixedContentMode={"compatibility"}
      javaScriptEnabled
      allowsBackForwardNavigationGestures
      setSupportMultipleWindows
      {...{ onMessage, onNavigationStateChange, onLoadEnd }}
      injectedJavaScript={injectJavascript}
    />
  );
};
