import React, { useEffect } from "react";

import { KeygenProvider, useKeygenContext } from "../../Contexts/KeygenContext";
import { useStatusContext } from "../../Contexts/StatusContext";
import { useUserContext } from "../../Contexts/UserContext";
import Result from "./result";

const MainForm = () => {
  const { token: { idToken: { jwtToken: token } } } = useUserContext();
  const { generateSecurityCerts, securityCerts } = useKeygenContext();
  const { setTitle, setSitePath, setMessage } = useStatusContext();
  const getCert = async () => {
    try {
      await generateSecurityCerts(token);
    } catch (e) {
      setMessage(e.message);
    }
  };

  useEffect(() => {
    setTitle("Security.dll Download");
    setSitePath([
      {
        label: `Tools`,
      },
      {
        label: "Security.dll Download",
      },
    ])
    getCert();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [token]);

  if (securityCerts) {
    return <Result {...securityCerts} />
  }

  return <h3>Generating certificates...</h3>
};

const SecurityDLL = () => (
  <KeygenProvider>
    <MainForm/>
  </KeygenProvider>
);

export default SecurityDLL;