let arrGlobals = [];

function readItem(_item, _asNumber) {
    let g_object;
    //console.log('reading: ' + _item + "Id");
    g_object = document.getElementById(_item + "Id");
    if (null != g_object) {
        if (_asNumber) {
            arrGlobals[_item] = Number(g_object.innerHTML);
        } else {
            arrGlobals[_item] = g_object.innerHTML;
        }
        if (arrGlobals['debugjs'] >= 1) { console.log(_item + ': ' + arrGlobals[_item]); }
    } else {
        console.log('g_object=null');
    }
}

function readGlobals() {

    // now 
    readItem('debugjs', true);
    //console.log('debugjs=' + arrGlobals['debugjs']);
    readItem('siteURL', false);
    readItem('path', false);
    readItem('root', false);
    readItem('participantAddr', false);
    readItem('agentAddr', false);
    readItem('websiteAddr', false);
    //readItem('GalleryAddr', false);

    // These two values are used for minting.
    readItem('agent', true);
    //readItem('website', true);

    readItem('theTitle', false);
    //readItem('customTitle', false);
    //readItem('customGallery', false);

    // URL values
    //readItem('contract', false);
    readItem('mobile', true);
    readItem('limit', true);
    readItem('maxWidth', true);

    //readItem('video_id', false);

    arrGlobals['visitor'] = null;
}



arrGlobals['ABI'] = [];
// ERC-721
//arrGlobals['ABI'].push({ "inputs": [], "name": "titled", "outputs": [{ "internalType": "address", "name": "", "type": "address" }], "stateMutability": "view", "type": "function" });
//arrGlobals['ABI'].push({ "inputs": [], "name": "owner", "outputs": [{ "internalType": "address", "name": "", "type": "address" }], "stateMutability": "view", "type": "function" });
arrGlobals['ABI'].push({ "inputs": [{ "internalType": "address", "name": "owner", "type": "address" }], "name": "balanceOf", "outputs": [{ "internalType": "uint256", "name": "", "type": "uint256" }], "stateMutability": "view", "type": "function" });
//arrGlobals['ABI'].push({ "inputs": [{ "internalType": "uint256", "name": "tokenId", "type": "uint256" }], "name": "tokenURI", "outputs": [{ "internalType": "string", "name": "", "type": "string" }], "stateMutability": "view", "type": "function" });
arrGlobals['ABI'].push({ "inputs": [{ "internalType": "bytes4", "name": "interfaceId", "type": "bytes4" }], "name": "supportsInterface", "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }], "stateMutability": "view", "type": "function" });
// IMetadataHashV1
arrGlobals['ABI'].push({ "inputs": [], "name": "projectDataCurrent", "outputs": [{ "internalType": "string", "name": "URI", "type": "string" }, { "internalType": "string", "name": "Project", "type": "string" }, { "internalType": "string", "name": "hash", "type": "string" }], "stateMutability": "view", "type": "function" });
// IPayV1
//arrGlobals['ABI'].push({ "inputs": [], "name": "payMintPrice", "outputs": [{ "internalType": "uint256", "name": "mintWei", "type": "uint256" }], "stateMutability": "view", "type": "function" });
//arrGlobals['ABI'].push({ "inputs": [{ "internalType": "uint256", "name": "_AgentId", "type": "uint256" }, { "internalType": "uint256", "name": "_websiteId", "type": "uint256" }], "name": "payMint", "outputs": [{ "internalType": "uint256", "name": "tokenId", "type": "uint256" }], "stateMutability": "payable", "type": "function" });
//arrGlobals['ABI'].push({ "inputs": [], "name": "payMintInfo", "outputs": [{ "internalType": "uint256", "name": "payAgentPennies", "type": "uint256" }, { "internalType": "uint256", "name": "payWebsitePennies", "type": "uint256" }, { "internalType": "uint256", "name": "inactivityDeadline", "type": "uint256" }, { "internalType": "uint256", "name": "minMintCount", "type": "uint256" }], "stateMutability": "view", "type": "function" });
//arrGlobals['ABI'].push({ "inputs": [{ "internalType": "address", "name": "_account", "type": "address" }], "name": "payAgentBalance", "outputs": [{ "internalType": "uint256", "name": "payBalanceWei", "type": "uint256" }, { "internalType": "uint256", "name": "payDeadline", "type": "uint256" }, { "internalType": "uint256", "name": "payCount", "type": "uint256" }], "stateMutability": "view", "type": "function" });
//arrGlobals['ABI'].push({ "inputs": [], "name": "payWithdraw", "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }], "stateMutability": "nonpayable", "type": "function" });
//arrGlobals['ABI'].push({ "inputs": [], "name": "payWithdrawTitled", "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }], "stateMutability": "nonpayable", "type": "function" });
// ICountV1
//arrGlobals['ABI'].push({ "inputs": [], "name": "totalSupply", "outputs": [{ "internalType": "uint256", "name": "", "type": "uint256" }], "stateMutability": "view", "type": "function" });
// IPennyOracleV1 (agent doesn't export this because it uses IPayV1)
//arrGlobals['ABI'].push({ "inputs": [], "name": "pennyPriceTfuel", "outputs": [{ "internalType": "uint256", "name": "pennyTfuelWei", "type": "uint256" }, { "internalType": "string", "name": "priceOfTfuel", "type": "string" }], "stateMutability": "view", "type": "function" });
// for IMintV1
//arrGlobals['ABI'].push({ "inputs": [], "name": "mintable", "outputs": [{ "internalType": "bool", "name": "bMintable", "type": "bool" }], "stateMutability": "view", "type": "function" });

// code assumes it supports erc-721
//arrGlobals['ABI'].push({ "inputs": [{ "internalType": "uint256", "name": "tokenId", "type": "uint256" }], "name": "tokenURI", "outputs": [{ "internalType": "string", "name": "", "type": "string" }], "stateMutability": "view", "type": "function" });


document.getElementById('walletAddress').innerHTML = '<span id="connectId" style="line-height:40px">Connect</span>';
arrGlobals['BalanceTfuel'] = null; // amount of Tfuel in account

document.addEventListener("DOMContentLoaded", async function () {
    console.log("In JavaScript video routine");

    readGlobals();
    console.log('done reading globals');


    if (window.ethereum) {
        await window.ethereum.request({ method: 'eth_accounts' });
        window.web3 = new Web3(window.ethereum);

        // first thing it to check chain id.
        var id = await web3.eth.getChainId();
        if (id != 361) {
            console.log("not Theta network");
            wrongNetwork();
        } else {
            console.log('correct network');

            // TODO: Title comes from contract metadata.
            document.getElementById("titleId").innerHTML = arrGlobals['theTitle'];

            g_accounts = await web3.eth.getAccounts();
            console.log('number of accounts: ' + g_accounts.length);
            console.log(g_accounts);
/*
            for (let acts = 0; acts < g_accounts.length; acts++) {
                root[g_accounts[acts]] = [];
            }
*/
            //console.log(root);
            arrGlobals['visitor'] = g_accounts[0];

            try {
                //console.log('getting balance');
                await web3.eth.getBalance(arrGlobals['visitor']).then(g_accountBalanceWei => {
                    // When we get our response, we'll calculate our balance and display what we can.
                    console.log("Balance: " + g_accountBalanceWei);
                    balance = Number(BigInt(g_accountBalanceWei) / BigInt(10000000000000000)) / 100;
                    arrGlobals['BalanceTfuelWei'] = g_accountBalanceWei;
                    arrGlobals['BalanceTfuel'] = balance;
                    button = '<span style="font-size:1em;"><center><b>';
                    accountShort = arrGlobals['visitor'].substring(0, 5).concat('...', arrGlobals['visitor'].substring(38, 42));
                    button = button.concat(accountShort, ' </b><br> <img src=\'https://www.thetascan.io/tfuel_dapp.png\'><span style="font-size:0.90em;"> ', arrGlobals['BalanceTfuel'], ' </span></center></span>');
                    document.getElementById('walletAddress').innerHTML = button
                });
            } catch (error) { }

            console.log("The Account: " + arrGlobals['visitor']);
            // if getAccounts is unsuccessful, we need to prompt user to connect MetaMask to
            // the website so that it can be used.

            if (arrGlobals['visitor'] === 'undefined') {
                console.log("Need to connect MetaMask");
            } else {
                console.log(arrGlobals);

                // fix layout here.
                //console.log("width: " + window.innerWidth);
                //console.log('maxWidth: ' + arrGlobals['maxWidth']);

                // how many per row?
                let iCount = parseInt(window.innerWidth / arrGlobals['maxWidth']);
                AdjustLayout(window.web3,iCount);
                //console.log("count for row: "+ iCount);
            }
        }
    } else {
        noMetamask();
    }
});

function theImage(_sec, _index, _blink) {

    let theImgId = 'imgsec' + _sec + 'index' + _index;
    let srcImg = document.getElementById(theImgId).innerHTML;
    //console.log(srcImg);
    let theLinkId = 'linksec' + _sec + 'index' + _index;
    let srcLink = document.getElementById(theLinkId).innerHTML;
    //console.log(srcLink);

    let thehrefId = 'hrefsec' + _sec + 'index' + _index;
    let hyperLink = '<a id="' + thehrefId + '" href="' + srcLink + '" target="_self">';

    // now get the section that needs the image
    let theItemId = 'itemsec' + _sec + 'index' + _index;
    let dstItemObj = document.getElementById(theItemId);
    if (dstItemObj != null) {
        let imgId = 'imgsec' + _sec + 'index' + _index;

        if (_blink) {
            dstItemObj.innerHTML = hyperLink + '<img id="' + imgId + '" class="reel" src="' + srcImg + '" >' + '</a>';
        } else {
            // special case mobile 
            let theClass = 'reel';
            if (arrGlobals['mobile'] == 1) {
                theClass = 'reelm';
            }
            dstItemObj.innerHTML = '<img id="' + imgId + '" class="'+theClass+'" src="' + srcImg + '" >';
            dstItemObj.style.opacity = '0.35';
        }
        dstItemObj.style.display = 'block';
    }
}

async function gateSection(_web3, _sec, _count, _contract) {
    // if we don't have a visitor address, we can't check to see if the visitor 
    // holds any resources.
    let bShow = false;
    if (typeof arrGlobals['visitor'] === 'undefined' || (arrGlobals['visitor'] === null)) {
        //console.log('all resources are disabled');
    } else {
        // only disable if visitor doesn't hold the resource, thus need to check
        // to make sure the resource is held.

        contractGate = new _web3.eth.Contract(arrGlobals['ABI'], _contract);

        let holdCount = await contractGate.methods.balanceOf(arrGlobals['visitor']).call();
        if (holdCount >= 1) {
            //console.log('holds one');
            bShow = true;
        }
    }

    if (!bShow) {
        //console.log("don't show the video");
        for (let j = 0; j < _count; j++) {
            theImage(_sec, j, false);
        }
    }
}

function AdjustLayout(_web3,_iCountPerRow) {
    //console.log("count for row: " + _iCountPerRow);

    let numOfSections = document.getElementById('countOfSections').innerHTML;
    //console.log("numOfSections: " + numOfSections);

    for (let i = 0; i < numOfSections; i++) {

        // get the number of videos for this section
        let iVideoCount = document.getElementById('videoCount' + i).innerHTML;
        //console.log("theVideoCount: " + iVideoCount);

        for (let j = 0; j < iVideoCount; j++) {

            theImage(i, j, true);

            // Adjust the laytout
            if (((j + 1)%_iCountPerRow)==0) {
                // terminate the row
                let theId = 'reelSec' + i + 'Row' + j;
                //console.log('turn this on: ' + theId);

                document.getElementById(theId).style.display = 'block';
            }
        }

        // Now, apply the gating if there is a contract regstered
        let secId = 'gatesec' + i;
        let secObj = document.getElementById(secId);
        if (secObj != null) {
            if (secObj.innerHTML != '') {
                //console.log(secObj.innerHTML);
                gateSection(_web3, i, iVideoCount, secObj.innerHTML);
            }
        }
    }
}

