import React from "react";
import { TraInfoEXWidget, getDelayData } from "./TraInfoEXWidget";
import { ToastAndroid } from "react-native";
import { InfoWidget, getInfoString } from "./InfoWidget";
import {
  FelicaQuickAccessWidget,
  getFelicaQuickAccessData,
} from "./FelicaQuickAccessWidget";
import { AS } from "../../storageControl";

export const nameToWidget = {
  JR_shikoku_train_info: TraInfoEXWidget,
  Info_Widget: InfoWidget,
  JR_shikoku_apps_shortcut: FelicaQuickAccessWidget,
};

export async function widgetTaskHandler(props) {
  const {
    widgetInfo,
    widgetAction,
    renderWidget,
    clickAction,
    clickActionData,
  } = props;
  const WidgetName = await AS.getItem(
    `widgetType/${widgetInfo.widgetId}`
  ).catch((e) => "JR_shikoku_train_info");
  // ToastAndroid.show(
  //   `Widget Action: ${JSON.stringify(widgetInfo.widgetId)}`,
  //   ToastAndroid.SHORT
  // );
  //ToastAndroid.show(`Widget Name: ${WidgetName}`, ToastAndroid.SHORT);
  switch (widgetAction) {
    case "WIDGET_ADDED":
    case "WIDGET_UPDATE":
    case "WIDGET_CLICK":
    case "WIDGET_RESIZED":
      if (widgetInfo.widgetName === "JR_shikoku_apps_shortcut") {
        const quickData = await getFelicaQuickAccessData();
        renderWidget(<FelicaQuickAccessWidget {...quickData} />);
        break;
      }

      switch (WidgetName) {
        case "Info_Widget": {
          const { time, text } = await getInfoString();
          renderWidget(
            <InfoWidget time={time} text={text && text.toString()} />
          );
          break;
        }
        case "JR_shikoku_train_info":
        default: {
          const { time, delayString } = await getDelayData();
          renderWidget(
            <TraInfoEXWidget time={time} delayString={delayString} />
          );
          break;
        }
      }

      break;

    case "WIDGET_DELETED":
      AS.removeItem(`widgetType/${widgetInfo.widgetId}`);
      break;
    default:
      break;
  }
}
