
// GLOBALS
let access_token = undefined
let access_token_expires = undefined
let access_token_expires_date = undefined

let client_id = '1781d9a5427e43e6ada3979925e1ce98'
let client_secret = TODO_REPLACE_SO_WE_DONT_CHECK_IN_SECRET
let auth = btoa(client_id + ":" + client_secret).toString('base64')

addEventListener('fetch', event => {
  event.respondWith(handleRequest(event.request))
})

async function handleRequest(request) {
  let debug = "";

  // simple bailout for any url I don't like
  if (!request.url.match(/armorystats\.info\/(character|profile)\/.*/i)) {
    return new Response('Hello, this is the api server for simplearmory.com');
  }

  var now = new Date();

  // if we don't have a token or its expired, lets go get another one
  if (!access_token || now > access_token_expires_date) {
    console.log('fetching new token...')

    let headers = {
        'Authorization': 'Basic ' + auth,
        'Content-Type': 'application/x-www-form-urlencoded'
    }
    
    const init = {
        method: 'POST',
        headers: headers,
        body: 'grant_type=client_credentials'
    }

    const response = await fetch('https://us.battle.net/oauth/token', init)
    const json = await response.json();

    var now = new Date();
    var tenMins = 10 * 60 * 1000;

    // store in global memory
    access_token = json.access_token;
    access_token_expires = now.getTime() + (json.expires_in * 1000) - tenMins;
    access_token_expires_date = new Date(access_token_expires);

    console.log(`got token: ${access_token} expires: ${access_token_expires} date: ${access_token_expires_date}`);
    debug = `FRESH: ${access_token_expires_date}`;
  } else {
    console.log(`using cached token: ${access_token} expires: ${access_token_expires} date: ${access_token_expires_date}`)
    debug = `EXISTING: ${access_token_expires_date}`;
  }

  let url_match = request.url.match(/(character|profile)\/(.+)\/(.+)\/(.+)/i);
  if (!url_match) {
    return new Response('Bad Request', { status: 400, statusText: 'Bad Request' });
  } 

  let region = url_match[2];
  let realm = url_match[3];
  let character = url_match[4];

  console.log(`region: ${region} realm: ${realm} character: ${character}`)

  let url;
  let api_response;

  if (url_match[1] === 'character') {
    url = `https://${region}.api.blizzard.com/wow/character/${realm}/${character}?fields=pets,mounts,achievements,guild,reputation`;
    api_response = await fetch(url, { headers: { 'Authorization': 'Bearer ' + access_token } } )

    // Copy the response so that we can modify headers.
    api_response = new Response(api_response.body, api_response)
  } else if (url_match[1] === 'profile') {
    url = `https://${region}.api.blizzard.com/profile/wow/character/${realm}/${character}?namespace=profile-${region}`;
    api_response = await fetch(url, { headers: { 'Authorization': 'Bearer ' + access_token } } )
    let json_response = await api_response.json()

    let achievements_url = json_response.achievements.href
    let achievements_response = await fetch(achievements_url, { headers: { 'Authorization': 'Bearer ' + access_token } } )
    json_response.achievements = await achievements_response.json()
    api_response = new Response(JSON.stringify(json_response), api_response)
  }

  // Add CORS so we can call it from our site
  api_response.headers.set("Access-Control-Allow-Origin", "*")
  api_response.headers.set("X-Debug", debug)

  return api_response
}


@@ -492,166 +492,8 @@
 like
-%0A  if (!request.url.match(/armorystats%5C.info%5C/(character%7Cprofile)%5C/.*/i)) %7B%0A    return new Response('Hello, this is the api server for simplearmory.com');%0A  %7D
 %0A%0A  
@@ -1730,44 +1730,59 @@
 ch(/
-(character%7Cprofile
+https?:%5C/%5C/.*%5C.(dev%7Cinfo)%5C/(.*?
 )%5C/(.
-+
+*?
 )%5C/(.
-+
+*?
 )%5C/(.
-+
+*
 )/i)
@@ -1890,17 +1890,16 @@
  %7D);%0A  %7D
- 
 %0A%0A  let 
@@ -1985,553 +1985,175 @@
 4%5D;%0A
-%0A
   
-console.log(%60region: $%7Bregion%7D realm: $%7Brealm%7D character: $%7Bcharacter%7D%60)%0A%0A  let url;%0A  let api_response;%0A%0A  if (url_match%5B1%5D === 'character') %7B%0A    url = %60https://$%7Bregion%7D.api.blizzard.com/wow/character/$%7Brealm%7D/$%7Bcharacter%7D?fields=pets,mounts,achievements,guild,reputation%60;%0A    api_response = await fetch(url, %7B headers: %7B 'Authorization': 'Bearer ' + access_token %7D %7D )%0A%0A    // Copy the response so that we can modify headers.%0A    api_response = new Response(api_response.body, api_response)%0A  %7D else if (url_match%5B1%5D === 'profile') %7B%0A   
+let site = url_match%5B5%5D;%0A  if (site) %7B%0A    site = %60/$%7Bsite%7D%60%0A  %7D%0A%0A  console.log(%60region: $%7Bregion%7D realm: $%7Brealm%7D character: $%7Bcharacter%7D site: $%7Bsite%7D%60)%0A    %0A  let
  url
@@ -2234,16 +2234,23 @@
 aracter%7D
+$%7Bsite%7D
 ?namespa
@@ -2278,242 +2278,16 @@
 ;%0A  
-  api_response = await fetch(url, %7B headers: %7B 'Authorization': 'Bearer ' + access_token %7D %7D )%0A    let json_response = await api_response.json()%0A%0A    let achievements_url = json_response.achievements.href%0A    let achievements_response
+let resp
  = a
@@ -2297,29 +2297,16 @@
 t fetch(
-achievements_
 url, %7B h
@@ -2367,156 +2367,60 @@
 %7D )%0A
-    json_response.achievements = await achievements_response.json()%0A    api_response = new Response(JSON.stringify(json_response), api_response)%0A  %7D
+%0A  let api_response = new Response(resp.body, resp);
 %0A%0A  

update proxy to always use profile and allow for generic passthrough