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

const _apiUrl: string = 'https://localhost:443/'

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

  //login user
  const loginUser = async (): Promise<void> => {
    try {
      const tmp = await axios.get(`${_apiUrl}OAuth2Login`, { withCredentials: true })
      console.log('lAAAAAA')
      console.log(tmp)
      await setUserContext()
    } catch (e) {
      setError(e)
    }
  }

  const logoutUser = async (): Promise<void> => {
    try {
      if (setUser) setUser(null)
      await axios.get(`${_apiUrl}Logout`)
    } catch (e) {
      setError(e)
    }
  }

  //set user in context and push them home
  const setUserContext = async (): Promise<void> => {
    try {
      const { data } = await axios.get(`${_apiUrl}api/common/WhoAmI`, {
        withCredentials: true,
      })
      if (data && setUser) {
        setUser(data)
        console.log('usertoContext', data)
        history.push('/editing')
      }
    } catch (e) {
      setError(e)
    }
  }

  return { loginUser, error, logoutUser }
}