# Sample code, software libraries, command line tools, proofs of concept, templates, or other related technology are provided as AWS Content or Third-Party Content under the AWS Customer Agreement, or the relevant written agreement between you and AWS (whichever applies). You should not use this AWS Content or Third-Party Content in your production accounts, or on production or other critical data. You are responsible for testing, securing, and optimizing the AWS Content or Third-Party Content, such as sample code, as appropriate for production grade use based on your specific quality control practices and standards. Deploying AWS Content or Third-Party Content may incur AWS charges for creating or using AWS chargeable resources, such as running Amazon EC2 instances or using Amazon S3 storage.

import json

html_content = """
<!DOCTYPE html>
<html>
  <head>
    <script src="https://aws-blogs-artifacts-public.s3.us-east-1.amazonaws.com/DBBLOG-3971/ethers-5.7.2.umd.min.js"
        type="application/javascript"></script>
  </head>
  <body>
    <h1>Authenticate with MetaMask to trigger training data upload</h1>

    <form id="fileinfo">
    <div>
      <label>Enter the IPFS CID your want to upload:</label>
      <input type="text" id="cid" name="cid" value="QmbYdXxJUa39AS69YSWJgh9q8a23qnHNCNQzTDtX2xAyXe" required />
    </div>
    <div>
      <label>Enter the filename you want to use:</label>
      <input type="text" id="filename" name="filename" value="ethereum-yellowpaper.pdf" required />
    </div>
    </form>


    <button onclick="signMessage()">Upload Training Data</button>
    <p id="status"></p>
    <script>

      // Helper function 
      function toHexString(byteArray) {
        return Array.prototype.map.call(byteArray, function(byte) {
          return ('0' + (byte & 0xFF).toString(16)).slice(-2);
        }).join('');
      }

      // Sign the upload request and send it to the API Gateway
      async function signMessage() {
        
        try {

          // Get the signer account using MetaMask
          const provider = new ethers.providers.Web3Provider(window.ethereum);
          await provider.send('eth_requestAccounts', []);
          const signer = provider.getSigner();

          // Generate random nonce to protect against replay attacks
          //const array = new Uint8Array(32);
          //self.crypto.getRandomValues(array);
          //const nonce = toHexString(array);;

          // Get form content
          const form = document.querySelector("#fileinfo");
          const formData = new FormData(form);
          const filename = formData.get("filename");
          const cid = formData.get("cid");


          // Sign message using the signer account and the nonce value
          const message = `Upload ${filename} with CID ${cid}.`;
          const signature = await signer.signMessage(message);
    
          formData.append("signature", signature);
          formData.append("message", message);

          const searchParams = new URLSearchParams(formData); 
	  const URL = "./ipfs2s3?"+searchParams;

          // Send the signed message to the API Gateway to trigger upload of training data
          const response = await fetch(URL, {
            method: 'GET',
            headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
            },
          });

          let answer = await response.json();
          console.log('Answer from server:',answer);
          var element = document.getElementById("status");
          element.innerHTML = answer;
        
        } catch (error) {
          console.error(error);
        }
      }
    </script>
  </body>
</html>
"""

json_response = {
    "isBase64Encoded": False,
    "statusCode": 200,
    "headers": { "content-type": "text/html" },
    "body": html_content
} 


def handler(event, context):
    return json_response

