import React from "react";
import { getIdToken, onIdTokenChanged } from "firebase/auth";
import { auth } from "../services/firebase";
import { TIPO_PROJECTO_JWT } from "../constants"
const localStorageKey = "usr_jwt";
const { REACT_APP_PROJECT: tipoProyecto  } = process.env;

const AppContext = React.createContext();

export function AppProvider(props) {
  const [token, setToken] = React.useState(null);

  React.useEffect(() => {
    if( tipoProyecto === TIPO_PROJECTO_JWT ) {
      const jwt = localStorage.getItem(localStorageKey)
      setToken(jwt)
    }
  }, []);

  React.useEffect(() => {
    if( tipoProyecto === TIPO_PROJECTO_JWT ) {
      if(token && token !== "") {
        localStorage.setItem(localStorageKey, token)
      }
    }
  }, [token]);

  React.useEffect(() => {
    if( tipoProyecto === TIPO_PROJECTO_JWT ) {
      return
    }

    let unsub = onIdTokenChanged(auth, (user) => {
      if(user) {
        getIdToken(user).then(token => {
          if(token) {
            setToken(token);
          }
        });  
      }
    });
    
    return () => unsub()
  }, []);
  
  const memData = React.useMemo(() => {
    return { token, setToken };
  }, [token, setToken]);

  return <AppContext.Provider value={memData} {...props} />;
}

export function useApp() {
  const context = React.useContext(AppContext);
  if (!context) {
    // eslint-disable-next-line no-throw-literal
    throw "error: app context not defined.";
  }
  return context;
}