import { useState } from "react";
import { w3cwebsocket as W3CWebSocket } from "websocket";
import styled from "styled-components";

const client = new W3CWebSocket(process.env.REACT_APP_BACKEND_URL);

const App = function App() {
  const [isOpen, setIsOpen] = useState(false);
  const [testFinished, setTestFinished] = useState(false);
  const [messages, setMesages] = useState([]);
  const addMessage = (message) => setMesages([...messages, message]);

  client.onopen = () => {
    setIsOpen(true);
    client.send(JSON.stringify({ topic: "start_test" }));
    console.log("OPEN");
  };
  client.onmessage = (message) => {
    const { topic, data } = JSON.parse(message.data);
    switch (topic) {
      case "data":
        console.log("MESSAGE", data);
        addMessage(data);
        break;
      case "end_test":
        console.log("ENDED TESTING");
        setTestFinished(true);
        break;
      default:
        console.error("Unknown Message Type");
    }
    const el = document.getElementById("log");
    el.scrollTop = el.scrollHeight;
  };

  const handleDownload = () => {
    console.log("Making CSV...");
    const header = Object.keys(messages[0]);
    let rows = [header, ...messages.map((message) => Object.values(message))];
    let csvContent =
      "data:text/csv;charset=utf-8," + rows.map((e) => e.join(",")).join("\n");
    var encodedUri = encodeURI(csvContent);
    console.log("Downloading CSV...");
    var link = document.createElement("a");
    link.setAttribute("href", encodedUri);
    link.setAttribute("download", "radiator_data.csv");
    document.body.appendChild(link);
    link.click(); // This will
  };

  return (
    <AppWrap>
      <Column>
        <Log id={"log"}>
          {isOpen && <Message key={"open"}>> Connection Open</Message>}
          {messages.map((message, i) => (
            <Message id={i + "msg"}>
              {"New Message: "} <br /> {JSON.stringify(message)}
            </Message>
          ))}
          {testFinished && <Message key={"finished"}>> Test Finished</Message>}
        </Log>
        <Buttons>
          {testFinished && messages.length > 0 && (
            <Button onClick={handleDownload}>download csv</Button>
          )}
        </Buttons>
      </Column>
    </AppWrap>
  );
};

const Message = styled.p`
  margin-top: 0;
  margin-bottom: 20px;
  width: 100%;
  word-wrap: anywhere;
  word-break: break-all;
`;

const Log = styled.div`
  overflow-y: scroll;
  background-color: black;
  color: #00ff66;
  font-size: 12px;
  padding: 12px;
  border-radius: 4px;
  width: 450px;
  flex-grow: 1;
  min-height: 200px;
  max-height: 60vh;
  font-family: source-code-pro, Menlo, Monaco, Consolas, "Courier New",
    monospace;
`;

const Button = styled.div`
  margin-right: 5px;
  border: 1px solid lightgrey;
  border-radius: 2px;
  font-size: 13px;
  height: 18px;
  font-weight: 500;
  padding: 5px;
  cursor: pointer;
  user-select: none;
`;

const Buttons = styled.div`
  height: 50px;
  margin-top: 5px;
  display: flex;
`;

const Column = styled.div`
  display: flex;
  flex-direction: column;
  justify-content: center;
`;

const AppWrap = styled.div`
  width: 100vw;
  height: 100vh;
  background-color: whitesmoke;
  display: flex;
  justify-content: center;
  align-content: center;
`;

export default App;
