import { Box } from "@mui/material";
import { useComponentAPI } from "hooks";
import { Component, Device } from "models";
import { pond } from "protobuf-ts/pond";
import { or } from "utils/types";
import { TranslateKey, TranslateValue } from "pbHelpers/Component";
import DiffHistory, { ListResult, Record } from "common/DiffHistory";

interface Props {
  device: Device;
  component: Component;
}

export default function ComponentHistory(props: Props) {
  const componentAPI = useComponentAPI();

  let list = (limit: number, offset: number): Promise<ListResult> => {
    return new Promise(resolve => {
      componentAPI
        .listHistory(props.device.id(), props.component.key(), limit, offset)
        .then((res: any) => {
          let records: Record[] = or(res.data.history, []).map((record: any) => {
            return {
              timestamp: or(record.timestamp, ""),
              user: or(record.user, ""),
              data: or(record.component, {}),
              status: or(record.progress, "Unknown")
            } as Record;
          });
          resolve({
            records: records,
            total: or(res.data.total, 0),
            offset: or(res.data.nextOffset, 0)
          });
        })
        .catch((_err: any) => {
          resolve({
            records: [] as Record[],
            total: 0,
            offset: 0
          });
        });
    });
  };

  let translateKey = (key: keyof any): string => {
    return TranslateKey(key as keyof pond.ComponentSettings);
  };

  let translateValue = (key: keyof any, obj: any): string => {
    return TranslateValue(
      key as keyof pond.ComponentSettings,
      pond.ComponentSettings.fromObject(obj)
    );
  };
  return (
    <Box>
      <DiffHistory
        name={props.component.name()}
        kind="component"
        list={list}
        translateKey={translateKey}
        translateValue={translateValue}
        showTitle={true}
      />
    </Box>
  );
}
