import { Box, Theme } from "@mui/material";
import { makeStyles } from "@mui/styles";
import { Component } from "models";
import { getMeasurementSummary } from "pbHelpers/ComponentType";
import { pond } from "protobuf-ts/pond";
import { quack } from "protobuf-ts/quack";
import { useEffect, useState } from "react";
import { or } from "utils";

interface Props {
  reading: pond.Measurement | undefined | null;
  component: Component;
  mode?: pond.BinMode;
  index?: number;
}

const useStyles = makeStyles((theme: Theme) =>
  ({
    "@keyframes ripple": {
      from: {
        transform: "scale(.8)",
        opacity: 1
      },
      to: {
        transform: "scale(1.4)",
        opacity: 0
      }
    },
    on: {
      boxShadow: `0 0 0 2px ${theme.palette.background.paper}`,
      animationName: "$ripple",
      animationDuration: "1.2s",
      animationTimingFunction: "ease-in-out",
      animationIterationCount: "infinite"
    },
    off: {
      backgroundColor: "transparent"
    }
  })
);

//NOREF: has no references in codebase, is this not used anywhere?
export default function SensorLight(props: Props) {
  const { mode, reading, component, index } = props;
  const classes = useStyles();
  const [color, setColor] = useState(undefined);

  useEffect(() => {
    if (
      reading &&
      reading.measurement &&
      reading.measurement.id &&
      reading.measurement.id.type !== null &&
      reading.measurement.id.type !== undefined
    ) {
      const grainCableFilters = () => {
        return {
          grainType: component.settings.grainType,
          grainFilledTo: component.settings.grainFilledTo
        };
      };

      let id = quack.ComponentID.fromObject(reading.measurement.id);
      let filters = { isTableCellMode: false };
      if (id.type === quack.ComponentType.COMPONENT_TYPE_GRAIN_CABLE) {
        filters = { ...filters, ...grainCableFilters() };
      }

      getMeasurementSummary(
        id.type,
        or(component.settings.subtype, 0),
        quack.Measurement.create(reading.measurement ? reading.measurement : undefined),
        filters
      ).then(summaries => {
        if (index && index < summaries.length) {
          setColor(summaries[index].colour);
        } else {
          summaries.forEach(sum => {
            setColor(sum.colour);
          });
        }
      });
    }
  }, [
    index,
    reading,
    component.settings.subtype,
    component.settings.grainFilledTo,
    component.settings.grainType
  ]);

  if (mode === undefined || mode === pond.BinMode.BIN_MODE_NONE || color === undefined) {
    return null;
  }

  return (
    <Box
      width="8px"
      height="8px"
      borderRadius="50%"
      style={{ backgroundColor: color }}
      className={classes.on}
    />
  );
}
