import { useEffect, useState } from "@theia/core/shared/react";
import * as React from "react";
import { createUseStyles } from "react-jss";
import { defaultJobGroupName, RCloneEndPoints } from "../../constants";
import fetchRClone from "../../helpers/fetchRClone";
import { isObjectEmpty } from "../../helpers/valueHelpers";
import useInterval from "../../hooks/useInterval";
import { IRCloneStats } from "../StorjWidget/StorjWidget.interface";
import { useCommonStyles } from "../StorjWidget/StorjWidget.style";
import StatRow from "./components/StatRow";

const useStyles = createUseStyles({
  statsContainer: {
    display: "flex",
    flexDirection: "column",
  },
});
type Props = {
  jobId?: number;
};
function Stats(props: Props) {
  const { jobId } = props;
  const [stats, setStats] = useState<IRCloneStats>({} as IRCloneStats);
  const [isLoading, setIsLoading] = useState(false);
  const classes = useStyles();
  const commonClasses = useCommonStyles();
  useEffect(() => {
    getStats();
  }, [jobId]);
  useInterval(() => {
    getStats();
  }, 2000);
  const getStats = async () => {
    if (!(jobId || jobId === 0)) {
      return;
    }
    const options = {
      body: JSON.stringify({
        group: jobId ? `${defaultJobGroupName}/${jobId}` : "",
      }),
    };
    if (!stats) {
      setIsLoading(true);
    }
    try {
      const res = await fetchRClone(RCloneEndPoints.stats, options);
      const json = await res.json();
      setStats(json);
    } catch (error) {
      console.error(error);
    } finally {
      setIsLoading(false);
    }
  };
  if (isLoading) {
    return (
      <div className={commonClasses.centeredContainer}>
        <i className="fa fa-spinner fa-spin fa-2x" />
      </div>
    );
  }
  if (isObjectEmpty(stats)) {
    return null;
  }
  return (
    <div>
      <h3>Job Stats</h3>
      <div className={classes.statsContainer}>
        <StatRow label="Total Bytes" value={stats.bytes} unit="B" />
        <StatRow label="Total Time" value={stats.transferTime} unit="s" />
        <StatRow label="Total Checks" value={stats.totalChecks} />
        <StatRow label="Estimated Time" value={stats.eta} unit="s" />
        <StatRow label="Average Speed" value={stats.speed} unit="B/s" />
        <StatRow label="Transferred Files" value={stats.transfers} />
        <StatRow label="Renamed Files" value={stats.renames} />
        <StatRow label="Deleted Files" value={stats.deletes} />
        <StatRow label="Number of Errors" value={stats.errors} />
        {stats.transferring?.length > 0 && (
          <div>
            <h4>Files:</h4>
            {stats.transferring?.map((item, index) => {
              return (
                <StatRow
                  key={index}
                  label={item.name}
                  value={item.percentage}
                />
              );
            })}
          </div>
        )}
      </div>
    </div>
  );
}

export default Stats;
