const accessTokenKeyName = "access_token"

async function setAccessToken({ authenCode, clientId, clientSecret, redirectUri }) {
  const uri = process.env.REACT_APP_URI_TOKEN
  const body = `grant_type=authorization_code&code=${authenCode}&client_id=${clientId}&client_secret=${clientSecret}&redirect_uri=${redirectUri}`;

  await fetch(uri, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    body
  })
    .then(resp => resp.json())
    .then(data => {
      localStorage.setItem(accessTokenKeyName, data.access_token)
    })
    .catch(error => {
      console.error(error)
    })
}

function getAccessToken() {
  const accessToken = localStorage.getItem(accessTokenKeyName)
  return accessToken
}

function removeAccessToken() {
  localStorage.removeItem(accessTokenKeyName)
}

async function getUserInfo(accessToken) {
  let uri = process.env.REACT_APP_URI_USERINFO
  uri += '?access_token=' + accessToken

  return await fetch(uri)
    .then(data => data.json())
    .then(userInfo => {
      return userInfo
    })
    .catch(error => console.error(error))
}


export {
  setAccessToken,
  getAccessToken,
  removeAccessToken,
  getUserInfo
}