import { Alert } from "@mui/material";
import React, { PropsWithChildren } from "react";
import { NetworkHookStatus, ServerApi } from "../../api/ServerApi";
import { AsyncWidget } from "../AsyncWidget";
import { CopyToClipboard } from "../CopyToClipboard";
import { InlineCode } from "../InlineCode";

export function NetworkHookStatusWidget(p: {
  hiddenIfInstalled: boolean;
}): React.ReactElement {
  const [status, setStatus] = React.useState<NetworkHookStatus | undefined>();

  const load = async () => {
    setStatus(await ServerApi.NetworkHookStatus());
  };

  return (
    <AsyncWidget
      loadKey={1}
      errMsg="Failed to get network status!"
      ready={!!status}
      load={load}
      build={() => <NetworkHookStatusWidgetInner {...p} status={status!} />}
    />
  );
}

function NetworkHookStatusWidgetInner(p: {
  status: NetworkHookStatus;
  hiddenIfInstalled: boolean;
}): React.ReactElement {
  if (p.status.installed && p.hiddenIfInstalled) return <></>;
  if (p.status.installed)
    return (
      <Alert
        variant="outlined"
        severity="success"
        style={{ margin: "20px 0px" }}
      >
        The network hook has been installed on this system.
      </Alert>
    );

  const makeExecutable = `chmod +x ${p.status.path}`;

  return (
    <Alert variant="outlined" severity="warning" style={{ margin: "20px 0px" }}>
      The network hook has not been detected on this system. It must be
      installed in order to expose ports from virtual machines through NAT on
      the network.
      <br />
      <br />
      In order to install it, please create a file named &nbsp;
      <CopyToClipboard content={p.status.path}>
        <InlineCode>{p.status.path}</InlineCode> &nbsp; with the following
      </CopyToClipboard>
      content:
      <br />
      <CopyToClipboard content={p.status.content}>
        <CodeBlock>{p.status.content}</CodeBlock>
      </CopyToClipboard>
      <br />
      Make sure that the created file is executable :
      <br />
      <CopyToClipboard content={makeExecutable}>
        <CodeBlock>{makeExecutable}</CodeBlock>
      </CopyToClipboard>
      <br />
      You will need then to restart both <InlineCode>
        libvirtd
      </InlineCode> and <InlineCode>VirtWeb</InlineCode>.
    </Alert>
  );
}

function CodeBlock(p: PropsWithChildren): React.ReactElement {
  return (
    <pre
      style={{
        backgroundColor: "black",
        color: "white",
        wordBreak: "break-all",
        wordWrap: "break-word",
        whiteSpace: "pre-wrap",
        padding: "10px",
        borderRadius: "5px",
      }}
    >
      {p.children}
    </pre>
  );
}
