import { useQuery, useResult } from '@vue/apollo-composable'
import gql from 'graphql-tag'

const logout = () => {
  //todo: add public param in route and check route

  if(!window.location.pathname.startsWith('/login')){
    //todo: add server side logout to delete cookies
    window.location.href = '/logout'
  }
}

let csrfToken
async function getCsrfToken() {
  if(csrfToken){
    return csrfToken
  }

  function getCookie(name) {
    let cookieValue = null

    if (document.cookie && document.cookie !== '') {
      const cookies = document.cookie.split(';')
      for (let i = 0; i < cookies.length; i++) {
        const cookie = cookies[i].trim()
        // Does this cookie string begin with the name we want?
        if (cookie.substring(0, name.length + 1) === (name + '=')) {
          cookieValue = decodeURIComponent(cookie.substring(name.length + 1))
          break
        }
      }
    }
    return cookieValue
  }
  csrfToken = getCookie('csrftoken')

  if(!csrfToken){

    csrfToken = fetch(window.location.protocol + "//" + window.location.hostname + ':' + process.env.VUE_APP_API_PORT+'/csrf')
      .then(response => response.json())
      .then(() => {
        return getCookie('csrftoken')
      })

  }
  return csrfToken
}

let auth
const useAuth = function(){
  if(!auth) {
    const { result, loading, onResult } = useQuery(gql`query profile {
                    profile {
                      id
                      id_disambiguated
                      username
                      full_name
                      email_signature
                      socket_token
                      process_count
                      notification_count
                      is_superuser
                      sec_role {
                        role_name
                        module_access
                      }
                    }
                  }
                `)

    const user = useResult(result, {}, data => data.profile)

    const hasAccess = (module, access) => {
      const lookup = module + '.' + (access === undefined ? 'base' : access)
      return user.value.sec_role && user.value.sec_role.module_access ? user.value.sec_role.module_access.includes(lookup) : false
    }

    auth = {
      user,
      loading,
      onResult,
      logout,
      hasAccess
    }
  }

  return auth
}

const Auth = {useAuth, getCsrfToken, logout}
export {Auth}
