import React, { useEffect, useState } from "react";
import { fetchLogs } from "../api";
import { matchesRegex, highlight } from "../utils";

export default function LogViewer({
  namespace,
  selection,
  regex,
  live
}) {
  const [logs, setLogs] = useState("");

  useEffect(() => {
    if (!selection) return;

    let interval;

    async function load() {
      const text = await fetchLogs({
        namespace,
        pod: selection.pod,
        container: selection.container
      });

      const filtered = text
        .split("\n")
        .filter((l) => matchesRegex(l, regex))
        .map(highlight)
        .join("\n");

      setLogs(filtered);
    }

    load();

    if (live) {
      interval = setInterval(load, 3000);
    }

    return () => clearInterval(interval);
  }, [selection, regex, live]);

  if (!selection) {
    return <div style={{ padding: 20 }}>Select container</div>;
  }

  return (
    <pre
      style={{
        background: "#0b0b0b",
        color: "#ddd",
        height: "100vh",
        overflow: "auto",
        padding: 12
      }}
    >
      {logs}
    </pre>
  );
}