import React from "react";
import { TraInfoEXWidget } from "./TraInfoEXWidget";
import dayjs from "dayjs";
import { ToastAndroid } from "react-native";

const nameToWidget = {
  // Hello will be the **name** with which we will reference our widget.
  JR_shikoku_train_info: TraInfoEXWidget,
};

export const getDelayData = async () => {
  // Fetch data from the server
  const time = dayjs().format("HH:mm");
  const delayString = await fetch(
    "https://script.google.com/macros/s/AKfycbyKxch7z7l8e07LXulRHqxjVoIiB13kcgvoToLE-rqlxLmLSKdlmqz0FI1F2EuA7Zfg/exec"
  )
    .then((response) => response.text())
    .then((data) => {
      if (data !== "") {
        return data.split("^");
      }
      return null;
    });
  ToastAndroid.show(`${delayString}`, ToastAndroid.SHORT);
  return { time, delayString };
};
export async function widgetTaskHandler(props) {
  const widgetInfo = props.widgetInfo;
  const Widget = nameToWidget[widgetInfo.widgetName];
  ToastAndroid.show(
    `Widget Action: ${JSON.stringify(props.widgetInfo.widgetId)}`,
    ToastAndroid.SHORT
  );
  const { time, delayString } = await getDelayData();
  switch (props.widgetAction) {
    case "WIDGET_ADDED":
    case "WIDGET_UPDATE":
    case "WIDGET_CLICK":
    case "WIDGET_RESIZED":
      // Not needed for now
      props.renderWidget(<Widget time={time} delayString={delayString} />);

      break;

    case "WIDGET_DELETED":
      // Not needed for now
      break;
    default:
      break;
  }
}
