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'] = [];
arrGlobals['ABI'].push({ "inputs": [{ "internalType": "address", "name": "owner", "type": "address" }], "name": "balanceOf", "outputs": [{ "internalType": "uint256", "name": "", "type": "uint256" }], "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');

    let titleObj = document.getElementById("titleId");
    if (null != titleObj) {
        titleObj.innerHTML = arrGlobals['theTitle'];
    }

    window.web3 = null;
    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');

            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']);
        }
    } else {
        noMetamask();
    }

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

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.

        if (null != _web3) {
            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);

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

            theImage(i, j, true);

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

                let theObj = document.getElementById(theId);
                if (null != theObj) {
                    theObj.style.display = 'block';
                }

            }

            // Getting the height of the video div doesn't really work.
            // thus we'll get the width and add a constant.
            // divsecXindexY
            let theId = 'divsec' + i + 'index' + j;
            let theItemObj = document.getElementById(theId);
            if (null != theItemObj) {

                if (theItemObj.clientWidth > iMaxHeight) {
                    iMaxHeight = theItemObj.clientWidth;
                    console.log('iMaxHeight: ' + iMaxHeight);
                }
            }
        }
        // now set them all to the same height
        for (let j = 0; j < iVideoCount; j++) {
            let theId = 'divsec' + i + 'index' + j;
            let theItemObj = document.getElementById(theId);
            if (null != theItemObj) {
                theItemObj.style.height = (iMaxHeight+10).toString() + 'px';
            }
        }
        iMaxHeight = 0;

        // 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);
            }
        }
    }
}

