<script setup lang="ts">
import { authServer, resourceServer, settings } from '@/main'
import { ref } from 'vue'
import { useKeycloak } from '@dsb-norge/vue-keycloak-js'

let resource = ref({})
const keycloak = useKeycloak()
let msg = ref("")

function manuallyRefreshAccessToken() {
  // We set a high minValidity to force a token refresh
  keycloak.keycloak && keycloak.keycloak.updateToken(5000)
}

async function doAuthenticatedRequest() {
  // Doesn't really go anywhere, but as you see from the headers in the request
  // it contains the latest access token at all times
  const response = await authServer.get('/oidc-test-web')
}

function getResourceUrl(url: string): string {
  return settings.resourceServerUrl + "/" + url
}

function logout() {
  keycloak.logoutFn && keycloak.logoutFn()
}

function accountManagemnt() {
  keycloak.accountManagement && keycloak.accountManagement()
}

async function get_resource(id: string) {
  if (!keycloak.keycloak) { return }
  await resourceServer.get(id).then(
    resp => {
      resource.value = resp['data']
      msg.value = ""
    }
  ).catch(
    err => {
      resource.value = []
      msg.value = `${err.message} (${err.response.statusText}): ${err.response.data["detail"]}`
    }
  )
}
</script>

<template>
  <div id="app">
    <h1>OIDC-test - web client</h1>
    <p class="center">
      Test the authentication and authorization, with OpenID Connect and OAuth2 with a Keycloak provider.
    </p>
    <div v-if="keycloak.authenticated" class="user-info">
      <p>Hey, {{ keycloak.idTokenParsed?.name }}</p>
      <img v-if="keycloak.idTokenParsed?.picture" :src="keycloak.idTokenParsed.picture" class="picture"></img>
      <div>{{ keycloak.idTokenParsed?.email }}</div>
      <div v-if="keycloak.resourceAccess && keycloak.resourceAccess['oidc-test']">
        <span>Roles for oidc-test:</span>
        <span v-for="role in keycloak.resourceAccess && keycloak.resourceAccess['oidc-test']['roles']" class="role">{{
          role }}</span>
      </div>
      <div v-if="keycloak.idTokenParsed?.oidc_provider">
        <span>Provider:</span>
        {{ keycloak.idTokenParsed.oidc_provider }}
      </div>
      <div v-if="keycloak.tokenParsed?.scope">
        <span>Scopes</span>:
        <span v-for="scope in keycloak.tokenParsed.scope.split(' ')" class="scope">{{ scope }}</span>
      </div>
      <button @click="accountManagemnt">Account management</button>
      <button @click="manuallyRefreshAccessToken">Refresh access token</button>
      <button @click="logout" class="logout">Logout</button>
    </div>
    <hr>
    <p class="center">
      Fetch resources from a resource server (at {{ settings.resourceServerUrl }})
      with your authentication token:
    </p>
    <div class="actions">
      <button @click="get_resource('time')">Time</button>
      <button @click="get_resource('bs')">BS</button>
    </div>
    <div class="resources">
      <div v-if="Object.entries(resource).length > 0" class="resource">
        <div v-for="(value, key) in resource">
          <div class="key">{{ key }}</div>
          <div v-if="key == 'sorry' || key == 'error'" class="error">{{ value }}</div>
          <div v-else class="value">{{ value }}</div>
        </div>
      </div>
    </div>
    <div v-if="msg" class="msg resource error">{{ msg }}</div>
    <div class="content">
      <p>
        These links should get different response codes depending on the authorization:
      </p>
      <div class="links-to-check">
        <a v-bind:href="getResourceUrl('public')">Public</a>
        <a v-bind:href="getResourceUrl('protected')">Auth protected content</a>
        <a v-bind:href="getResourceUrl('protected-by-foorole')">Auth + foorole protected content</a>
        <a v-bind:href="getResourceUrl('protected-by-foorole-or-barrole')">Auth + foorole or barrole protected
          content</a>
        <a v-bind:href="getResourceUrl('protected-by-barrole')">Auth + barrole protected content</a>
        <a v-bind:href="getResourceUrl('protected-by-foorole-and-barrole')">Auth + foorole and barrole protected
          content</a>
        <a v-bind:href="getResourceUrl('fast_api_depends')" class="hidden">Using FastAPI Depends</a>
        <a v-bind:href="getResourceUrl('introspect')">Introspect token (401 expected)</a>
      </div>
    </div>
    <div v-if="settings.tokenSandbox" class="token-info">
      <hr>
      <div>
        <h2>idToken</h2>
        <div class="token">
          <div v-for="(value, key) in keycloak.idTokenParsed">
            <div class="key">{{ key }}</div>
            <div class="value">{{ value }}</div>
          </div>
        </div>
        <h2>access token</h2>
        <div class="token">
          <div v-for="(value, key) in keycloak.tokenParsed">
            <div class="key">{{ key }}</div>
            <div class="value">{{ value }}</div>
          </div>
        </div>
        <h2>refresh token</h2>
        <div class="token">
          <div v-for="(value, key) in keycloak.refreshTokenParsed">
            <div class="key">{{ key }}</div>
            <div class="value">{{ value }}</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
