import React, { useState, useEffect, useMemo, useContext } from "react"
import { getAccessToken } from "./AuthDataSource"
import { getUserInfo } from "./AuthDataSource"

const AuthContext = React.createContext()

const initialAuthData = {}

function AuthProvider({ ...props }) {
  const [authData, setAuthData] = useState()
  
  useEffect(() => {        
    const accessToken = getAccessToken()

    if (accessToken) {      
      getUserInfo(accessToken).then(user => {        
        if (user) {          
          setAuthData(user)
        }
      })
    }
  }, [])

  const onLogout = () => setAuthData(initialAuthData)

  const onLogin = authData => setAuthData(authData)

  const authDataValue = useMemo(() => ({ authData, onLogin, onLogout }), [authData])  

  return <AuthContext.Provider value={authDataValue} {...props} />
}

export const useAuthContext = () => useContext(AuthContext)

export default AuthProvider