import { useState, useEffect, useRef } from "react";
import Box from "@mui/material/Box";
import Button from "@mui/material/Button";
import TextField from "@mui/material/TextField";
import RconSocket from "./RconSocket.js";
import "@mcl/css/rcon.css";

export default function RconView(props) {
  const { serverId } = props;
  const logsRef = useRef(0);
  const [cmd, setCmd] = useState("");
  const [logs, setLogs] = useState([]);
  const [rcon, setRcon] = useState();
  const updateCmd = (e) => setCmd(e.target.value);

  const disconnectRcon = () => {
    if (!rcon || typeof rcon.disconnect !== "function") return;
    rcon.disconnect();
  };

  useEffect(
    function () {
      if (!serverId) return;
      const rs = new RconSocket(setLogs, serverId);
      setRcon(rs);
      return disconnectRcon;
    },
    [serverId],
  );

  useEffect(
    () => logsRef.current.scrollTo(0, logsRef.current.scrollHeight),
    [(rcon ?? {}).logs],
  );

  function sendCommand() {
    rcon.send(cmd);
    setCmd("");
  }

  return (
    <Box>
      <div className="rconLogsWrapper" ref={logsRef}>
        {logs.map((v, k) => (
          <Box key={k}>
            {v}
            <br />
          </Box>
        ))}
      </div>
      <Box className="rconActions">
        <TextField
          id="outlined-basic"
          label="Command"
          variant="outlined"
          value={cmd}
          onChange={updateCmd}
          disabled={!(rcon && rcon.rconLive)}
        />
        {rcon && rcon.rconLive && <Button onClick={sendCommand}>Send</Button>}
        {!(rcon && rcon.rconLive) && (
          <Button color="secondary">Not Connected</Button>
        )}
      </Box>
    </Box>
  );
}
