import React, { useContext, useState } from "react";

import api from "../../services/suppliersAPI";

const KeygenContext = React.createContext();

export const KeygenProvider = ({ children }) => {
  const [busy, setBusy] = useState(false);
  const [securityCerts, setSecurityCerts] = useState(null);

  const generateSecurityCerts = async (token) => {
    setBusy(true);

    try {
      const data = await api.getManufactureCert(token);

      if (data.error) throw new Error(data.message);

      setSecurityCerts(data);
    } finally {
      setBusy(false);
    }
  };

  return (
    <KeygenContext.Provider
      value={{
        busy,
        securityCerts,
        generateSecurityCerts,
      }}
    >
      {children}
    </KeygenContext.Provider>
  );
};

export const useKeygenContext = () => useContext(KeygenContext);
