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

interface Props {
  device: Device;
}

export default function DeviceHistory(props: Props) {
  const deviceAPI = useDeviceAPI();

  let list = (limit: number, offset: number): Promise<ListResult> => {
    return new Promise(resolve => {
      deviceAPI
        .listHistory(props.device.id(), limit, offset)
        .then((res: any) => {
          let records: Record[] = or(res.data.history, []).map((record: any) => {
            //console.log(record)
            return {
              timestamp: or(record.timestamp, ""),
              user: or(record.user, ""),
              data: or(record.device, {}),
              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.DeviceSettings);
  };

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