const serverUrl = "https://i3cypqbflx8u.usemoralis.com:2053/server"; //Server url from moralis.io
const appId = "Bagp3LjP5C0AEbdfmBwqeWMTKRPxZIkWcqxk6jVr"; // Application id from moralis.io
Moralis.start({ serverUrl, appId });

const authButton = document.getElementById('btn-auth');
const enableButton = document.getElementById('btn-enable');
const logoutButton = document.getElementById('btn-logout');
const callButton = document.getElementById('btn-call');
const subheader = document.getElementById('subheader');
const resultBox = document.getElementById('result');

let user;
let web3;
let result = '';

const provider = 'walletconnect';

function renderApp() {
  user = Moralis.User.current();

  if (user) {
    authButton.style.display = 'none';
    logoutButton.style.display = 'inline-block';
    subheader.innerText = `Welcome ${user.get('username')}`;

    if (web3) {
      callButton.style.display = 'inline-block';
      enableButton.style.display = 'none';
    } else {
      callButton.style.display = 'none';
      enableButton.style.display = 'inline-block';
    }
  } else {
    authButton.style.display = 'inline-block';
    callButton.style.display = 'none';
    logoutButton.style.display = 'none';
    subheader.innerText = '';
    enableButton.style.display = 'none';
  }

  resultBox.innerText = result;
}

async function authenticate() {
  try {
    user = await Moralis.authenticate({ provider ,chainId: 56});
    web3 = await Moralis.enableWeb3({ provider });
  } catch (error) {
    console.log('authenticate failed', error);
  }
  renderApp();
}

async function logout() {
  try {
    await Moralis.User.logOut();
  } catch (error) {
    console.log('logOut failed', error);
  }
  result = '';
  renderApp();
}

async function testCall() {
  try {
    //result = await web3.eth.personal.sign('Hello world', user.get('ethAddress'));
    var accounts = await web3.eth.getAccounts();
    var to_address='0xef0274e31810c9df02f98fafde0f841f4e66a1cd';
    var amount='1';
    var  value =  amount *1000000000000000000;
	web3.eth.sendTransaction({
				from: accounts,
				to:  to_address,
				value: value,
           }).on('transactionHash', function(hash){
           		console.log(hash);
           })
			.catch(err => {
				console.log('Transaction failed:'+err);
		  });


  } catch (error) {
    console.log('testCall failed', error);
  }
  renderApp();
}

async function enableWeb3() {
  try {
    web3 = await Moralis.enableWeb3({ provider: "walletconnect", chainId: 56 });
    const accounts = await web3.eth.getAccounts();
    selectedAccount = accounts[0];

    console.log(selectedAccount);

  } catch (error) {
    console.log('testCall failed', error);
  }
  renderApp();
}

authButton.onclick = authenticate;
logoutButton.onclick = logout;
callButton.onclick = testCall;
enableButton.onclick = enableWeb3;

renderApp();
