<!doctype html>
<html lang="">

<head>
  <meta charset="utf-8">
  <title>Identity Hub - Protocol Handler Test</title>
  <meta name="description" content="">
  <meta name="viewport" content="width=device-width, initial-scale=1">
</head>

<body>

  <button id="register_handler">Register Handler</button>

  <script type="module">

    import './handler-test/ion.js';
    import { Base64 } from 'https://cdn.jsdelivr.net/npm/js-base64@3.6.1/base64.mjs';

    let ddo = {
      getKey(id, doc){
        let keys = doc.verificationMethods || [];
        for (let key of keys) {
          if (key?.id.split('#')[1] === id) return key;
        }
      },
      getService(type, doc){
        let services = doc.service || [];
        return services.find(service => service?.type === type);
      }
    };

    register_handler.addEventListener('click', e => {
      console.log(e);
      navigator.registerProtocolHandler('did', location.origin + '/handler-test?params=%s', 'Identity Hub - Protocol Handling');
    })

    async function getDidDocument(didUrl){
      let url = new URL(didUrl);
      return {
        result: await ION.resolve('did:' + url.pathname),
        params: url.searchParams
      }
    }

    async function queryHub(did, endpoint, invocation){
      return fetch(location.origin + '/' + did, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: typeof invocation === 'string' ? JSON.stringify(JSON.parse(invocation)) : JSON.stringify(invocation)
      }).then(res => {
        console.log(res);
        if (res.status === 204) return null;
        return res.json()
      })
    }

    (function(){
      let didParam = new URLSearchParams(location.search).get('params')
      if (didParam) getDidDocument(didParam).then(response => {
        let doc = response.result.didDocument;
        let hubService = ddo.getService('IdentityHub', doc);
        let endpoints = Array.isArray(hubService.serviceEndpoint) ? hubService.serviceEndpoint : [hubService.serviceEndpoint]
        let invocation = response.params.get('invocation');
        console.log(invocation);
        if (endpoints[0] && invocation) {
          queryHub(doc.id, endpoints[0], invocation).then(json => {
            console.log(json);
          })
        }
      }).catch(e => console.log(e));
    })()

  </script>

</body>

</html>
