import axios from 'axios'
import { useContext, useState } from 'react'
import { useHistory } from 'react-router-dom'
import { links } from '../components/Routes/Router'
import { UserContext } from './userContext'

interface Auth {
  loginUser: () => Promise<void>
  error: null
  logoutUser: () => void
}
export const useAuth = (): Auth => {
  const [error, setError] = useState<any>(null)
  const { setUser } = useContext(UserContext)
  const history = useHistory()

  //login user
  const loginUser = async (): Promise<void> => {
    try {
      window.location.href = '/OAuth2Login'
      await setUserContext()
    } catch (e) {
      setError(e)
    }
  }

  const logoutUser = async (): Promise<void> => {
    try {
      if (setUser) setUser(null)
      window.location.href = '/Logout'
    } catch (e) {
      setError(e)
    }
  }

  //set user in context and push them home
  const setUserContext = async (): Promise<void> => {
    try {
      const { data } = await axios.get(`/api/common/WhoAmI`)
      if (data && setUser) {
        setUser(data)
        history.push(links.newsletter.path)
      }
    } catch (e) {
      setError(e)
    }
  }

  return { loginUser, error, logoutUser }
}