import React, { useContext, useState } from "react";
import { NetworkStateContext, NetworkDispatchContext } from "../../network/state/contexts";
import MachinesListComponent from "./MachinesListComponent";
import PageTitle from "../../../components/common/PageTitle";
import { useTranslation } from "react-i18next";
import ViewModeSelection from "./ViewModeSelection";
import { ViewModes } from "../constants";
import { endpoints } from "../../../utils/api";
import { useSWR, fetcher } from "units/swr";
import { blip } from "utils";
import { Machine } from "types";

const MachinesContainer: React.FC = () => {
  const [viewMode, setViewMode] = useState(null);

  const state = useContext(NetworkStateContext);
  const dispatchActions = useContext(NetworkDispatchContext);
  const { t } = useTranslation();

  const url = state.network.machines.loaded ? null : endpoints.network.machines;
  useSWR<Machine[], Error>(url, fetcher, {
    revalidateOnFocus: false,
    onError: err => blip.error(err.message),
    onSuccess: machines => {
      const data = Object.assign(machines, { loaded: true });
      dispatchActions.onNetworkChange("machines", data);
    }
  });

  return (
    <>
      <PageTitle
        text={t("Menu.Machines")}
        toolBar={<ViewModeSelection callback={setViewMode} initialMode={ViewModes.TABLE} />}
      />
      {viewMode && <MachinesListComponent machines={state.network.machines} viewMode={viewMode} />}
    </>
  );
};

export default MachinesContainer;
