// Set up the ADAL instance, we will use the throughout the app
export var adalInstance = new AuthenticationContext({
  instance: 'https://login.microsoftonline.com/',
  
  // The client ID of the app from the Azure Portal
  clientId: 'aabbccee-aabb-1122-3344-556677889900',
  
  // Where do we want to go after logging out
  postLogoutRedirectUri: window.location.origin, 
  
  endpoints: {
    // The domain of API (requsets are made TO)
    // And the same client id as above
    "https://YOURAPIDOMAIN.azurewebsites.net/": "aabbccee-aabb-1122-3344-556677889900" 
  }
})

export function authenticateToken() {
    if (adalInstance.getCachedUser()) {
        // If we have a cached login, use it
        return true
    }

    if (adalInstance.isCallback(window.location.hash)) {
        // This happens after the AD login screen,
        // handleWindowCallback will use the hash to
        // complete the login
        adalInstance.handleWindowCallback()
        return true
    }

    // Not logged in
    return false
}

export function azureApiRequest(method, resource, body) {
    var resourceUrl = apiUrl + resource;
    
    // Use the client ID of your app for this call,
    // same as in the configuration earlier
    var bearerToken = adal.getCachedToken('aabbccee-aabb-1122-3344-556677889900')
   
   var opts = {
        method: method,
        headers: {
            'Authorization': 'Bearer ' +  bearerToken
        }
    }

    // I'm using JSON for my API, you can change this to your
    // heart's desire
    if (body) {
        opts.body = JSON.stringify(body)
        opts.headers['Content-Type'] = 'application/json'
    }

    return fetch(resourceUrl, opts)
        .then(response => {
            return response.json()
        }).catch(function(error) {
            console.log("Network problem: " + error)
            // Inspect the error further to see what is actually wrong
        }
    )
}