<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

<script>

  const setSession = async (key, item) => {
      localStorage.setItem(key,item);
  }

  const getSession = async (key) => {
      return localStorage.getItem(key);
  }

  const setObjectSession = async (key, obj) => {
    localStorage.setItem(key,JSON.stringify(obj));
  }

  const getObjectSession = async (key) => {
     return JSON.parse(localStorage.getItem(key));
  }

  const callBackend = async (messageRequest) => {

    try {
        const response = await axios.post('/api',messageRequest);
        return response.data;
    } catch(err) {
       console.error(`Error on ${messageRequest.service}`,err.message);
       alert(`Error --> ${err.message}`);
       return null;
    }

  }

  const loadingWallet = (html) => {

    if(!html){
        html = `<div class="spinner-border text-primary " role="status">
                    <span class="sr-only">Carregando..</span>
                </div>`;
    }

    $('#dadosDash').html(html);

  }

  const createAddress = async () => {

    const messageRequest = {
        service:'createWallet',
        data:null
    }

    let html = ' ';

    loadingWallet(null);

    const response = await callBackend(messageRequest);

    const dash_wallet = {
        wallet: response.address,
        mnemonic:response.mnemonic
    }

    await setObjectSession('dash_wallet',dash_wallet);

    html += `Carteira Dash:<strong>${response.address}</strong></br>`;
    html += `Mnemonic da carteira:<strong>${response.mnemonic}</strong>`;

    loadingWallet(html);

  }

  const checkCarteiraDash = async () => {
    
    const carteiraDash = await getObjectSession('dash_wallet');
 
    let html = ' ';

    loadingWallet(null);

    if(carteiraDash) {
        html += `<strong>Carteira Dash:</strong>${carteiraDash.wallet}</br>`;
        html += `<strong>Mnemonic da carteira:</strong>${carteiraDash.mnemonic}`;
        $('#mnemonic').val(carteiraDash.mnemonic);
    } else {
        html = ` <button type="button" class="btn btn-primary" onclick="createAddress();" >Criar carteira de Dash</button> `;  
    }

    loadingWallet(html);

  }

  const createIdentity = async () => {

      const mnemonic = $('#mnemonic').val();

      const messageRequest = {
        service:'createIdentity',
        data:{
          mnemonic
        }
      }

      console.log('mnemonic',mnemonic);

      const response = await callBackend(messageRequest);

      console.log('response',response.data);
    

  }


  (async () => {
    try {

      await checkCarteiraDash();

    } catch (e) {
      console.log(e);
    }
  })();


</script>