import { Box, Button, Grid, TextField } from "@mui/material";
import { NfcCommand } from "pages/Nfc";
import { useSnackbar } from "providers";
import { useState } from "react";

interface Props {
  onCommandRun: (command: NfcCommand[]) => void;
}

export default function NfcCommands(props: Props) {
  const { onCommandRun } = props;
  const [textCommand, setTextCommand] = useState("");
  const { openSnack } = useSnackbar();
  const ndef = window.NDEFReader ? new NDEFReader() : undefined;

  const writeCommand = (commandData: string) => {
    if (ndef) {
      ndef
        .write({
          records: [{ recordType: "text", data: commandData }]
        })
        .then(resp => {
          openSnack("Comand sent");
          onCommandRun([{ type: "text", command: "write", data: commandData }]);
        })
        .catch(error => {
          openSnack("Failed to send command");
        });
    }
  };

  const readCommand = () => {
    if (ndef) {
      ndef.scan().then(() => {
        //the scan started looking for the tag
        openSnack("Starting Scan");

        //the tag is found and can be read
        ndef.onreading = event => {
          let records: NfcCommand[] = [];
          openSnack("Scan Complete");
          //goes through the records found on the tag
          event.message.records.forEach(record => {
            //if the records type is set as tex
            if (record.recordType === "text") {
              //create a decoder using the records encoding method
              let decoder = new TextDecoder(record.encoding);
              //push the record type and the decoded data into the records to show in the command history
              records.push({
                type: record.recordType,
                command: "read",
                data: decoder.decode(record.data) //decode the record into a string to display
              });
            }
          });
          onCommandRun(records);
        };

        ndef.onreadingerror = event => {
          openSnack("Failed to Complete Scan");
        };
      });
    }
  };

  return (
    <Box>
      <TextField
        label="NFC Command entry"
        fullWidth
        value={textCommand}
        onChange={e => {
          setTextCommand(e.target.value);
        }}
        style={{ paddingTop: 5, paddingBottom: 5 }}
      />
      <Grid container spacing={2}>
        <Grid item>
          <Button
            variant="contained"
            color="primary"
            onClick={() => {
              if (ndef) {
                writeCommand(textCommand);
              } else {
                openSnack("Browser does not support web nfc");
              }
            }}>
            Write to NFC Tag
          </Button>
        </Grid>
        <Grid item>
          <Button
            variant="contained"
            color="primary"
            onClick={() => {
              if (ndef) {
                readCommand();
              } else {
                openSnack("Browser does not support web nfc");
              }
            }}>
            Read NFC Tag
          </Button>
        </Grid>
      </Grid>
    </Box>
  );
}
