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('account', false);

    readItem('video_id', false);
    readItem('video_yt', false);

    arrGlobals['visitor'] = null;
}



//let g_arrTrxns = [];
//let g_iCount = 0;

//let g_lastBlock = 24686000;
//let g_lastBlock = 14686000;
//let g_iLimit = 20;


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

let g_accounts = [];
//let g_visitor; // This is just [0] in g_accounts

/*
This routine is going to fetch all the transactions for each of the
accounts that are in the metamask wallet. They will be stored in the
root. Each account will be an index into the array.
*/
//let root = [];


let g_contracts = [];


// colors
let g_bkg = [];
g_bkg['active'] = '#b0f5c6';   // a green
g_bkg['inactive'] = '#f3f5ab'; // a yellow
g_bkg['standard'] = '#f0edeb'; // a grey

/*
root - is an array of accounts.
root[account#] - is an array that holds transactions, offset and contracts
transaction array = root[account#]['trxns']
offset = root[account#]['offset']

*/

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");
                //noConnection();
            } else {

                console.log(arrGlobals);
                //console.log('fetch and show video');
/*
                if (arrGlobals['video_id']) {
                    showVideo();
                } else if (arrGlobals['video_yt']) {
                    showVideo();
                } else {
                    //console.log("do we support a contract?");
                    ReadContract(window.web3,arrGlobals['contract']);
                }
*/
            }
        }

    } else {
        noMetamask();
    }

});
/*
//
// We either have a youtube video or a Theta DRM video
//
function showVideo() {
    // Either case, we need the width and height
    let theWidth = window.innerWidth;
    let theHeight = parseInt((theWidth * 9 / 16));
    //console.log(theWidth + ' ' + theHeight);

    if (typeof arrGlobals['video_yt'] !== 'undefined' &&
        arrGlobals['video_yt'] !== null &&
        arrGlobals['video_yt'] != '') {
        //console.log('We have YouTube video: ' + arrGlobals['video_yt']);

        let theObj = document.getElementById('videoRowId');
        if (theObj != null) {
            theObj.style.width = theWidth.toString() + 'px';
            theObj.style.height = theHeight.toString() + 'px';
            theObj.style.display = 'block';
        }
    }
    else if (typeof arrGlobals['video_id'] !== 'undefined' &&
        arrGlobals['video_id'] !== null &&
        arrGlobals['video_id'] != '') {
        //console.log('We have Theta DRM video: ' + arrGlobals['video_id']);

        let theObj = document.getElementById('videoRowId');
        if (theObj != null) {
            let theSrc = "https://player.thetavideoapi.com/video/" + arrGlobals['video_id'];
            console.log(theSrc);

            // write into the div the iframe
            let theFrame = '<iframe id="iframeId" src=' + theSrc + ' width=' + theWidth.toString() + 'px height=' + theHeight.toString() + 'px scrolling="no" border="0" allow="fullscreen"></iframe>';
            theObj.innerHTML = theFrame;

            theObj.style.width = theWidth.toString() + 'px';
            theObj.style.height = theHeight.toString() + 'px';
            theObj.style.display = 'block';
        }
    }
}

// Load the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

// Replace the 'ytplayer' element with an <iframe> and
// YouTube player after the API code downloads.
var player;
function onYouTubePlayerAPIReady() {
    let theWidth = window.innerWidth;
    let theHeight = (theWidth * 9 / 16);

    //console.log('This: '+arrGlobals['video_yt']);

    if (typeof arrGlobals['video_yt'] !== 'undefined' &&
        arrGlobals['video_yt'] !== null &&
        arrGlobals['video_yt'] != '') {

        player = new YT.Player('ytplayer', {
            height: theHeight,
            width: theWidth,
            videoId: arrGlobals['video_yt']
        });
    }
}


//
// Read the metadata from the contract.
//
async function readMetadata(_contractIndex) {

    // This nested code fetches the project info writes it and shows it.
    g_contracts[_contractIndex]['obj'].methods.projectDataCurrent().call().then(metadataObj => {
        //console.log('metadata Object:');
        //console.log(metadataObj);

        //TODO: Need to validate the URL returned from the contract is valid

        // The base URL will be slash terminated in the contract. Thus, build the path out
        // here.
        let projectURL = metadataObj[0] + metadataObj[1] + ".json";
        //console.log(projectURL);

        $url = arrGlobals['siteURL'] + 'dsn/?data=' + projectURL;
        //console.log($url);

        // Now let's fetch the project json file
        fetch($url).then(response => {
            response.json().then(projectObj => {
                //console.log("projectObj");
                //console.log(projectObj);

                // When we successfully get our information, we change the name
                // to what we fetched.
                document.getElementById("titleId").innerHTML = projectObj.name;

                // It's an object.
                if (typeof projectObj.video_id !== 'undefined' &&
                    projectObj.video_id !== null &&
                    projectObj.video_id.length > 0) {
                    //console.log('video_id: ' + projectObj.video_id);

                    arrGlobals['video_id'] = projectObj.video_id;
                    showVideo();

                } else if (typeof projectObj.video_reel !== 'undefined' &&
                    projectObj.video_reel !== null &&
                    projectObj.video_reel.length > 0) {
                    //console.log("point to video reel!");

                    // get the noVideoId block, modify the text and display
                    let theObj = document.getElementById('noVideoId');
                    if (theObj != null) {
                        //console.log(arrGlobals['siteURL'] + 'dsn');
                        //console.log(projectObj.video_reel);

                        // build hyperlink to home location
                        let theLink = arrGlobals['siteURL']+'dsn/reel/?reel=' + projectObj.video_reel;
                        let thehyperLink = '<a href="'+theLink+'" target="_self">here</a>';

                        theObj.innerHTML = "Video Reel can be found " + thehyperLink+".";
                        theObj.style.display = 'block';
                    }

                } else {
                    // Need to display message that this Selene Network compatible NFT
                    // does not report supporting any tokengated video.
                    // noVideoId
                    document.getElementById('noVideoId').style.display = 'block';
                }
            });
        });

    });
}


//
// This routine is designed to look in a wallet for all the contracts
// and enumerate them. 
//
// returns an index into the array of contract objects
function getContractObjIndex(_web3, _contract) {
    let it = 0;
    for (it = 0; it < g_contracts.length; it++) {
        if (_contract == g_contracts[it]['addr']) {
            //console.log('found obj for: ' + _contract);
            return it;
        }
    }
    // else, we allocate it
    g_contracts[it] = [];
    g_contracts[it]['obj'] = new _web3.eth.Contract(arrGlobals['ABI'], _contract);
    g_contracts[it]['addr'] = _contract;
    //console.log('created obj for: ' + it);
    return it;
}

//
// This routine performs an interface query to see if the contract supports IMetadataV1.
// If so, we'll fetch that and parse out the video_id information.
//
async function ReadContract(_web3,_contract) {

    // prepare the contractobject with the contract address
    let theContractIndex = getContractObjIndex(_web3, _contract);

    try {
        await g_contracts[theContractIndex]['obj'].methods.supportsInterface(arrGlobals['I']['IMetadataV1']['id']).call().then(theResult => {
            if (theResult) {
                // supports our interface
                //console.log('supports interface');
                //console.log(theTrxnObj.contract + ' Supports request');
                //enhancedToken(theContractIndex, _acts, _index);
                readMetadata(theContractIndex);
            } else {
                // doesn't support our interface.
                console.log('does not support interface');
                //console.log(theTrxnObj.contract + ' No Support');
                //standardToken(theContractIndex, _acts, _index);
            }
        });
    } catch (err) {
        console.log(err);
    }
}
*/