// script goes here.

// The custom functionality that this DAT is providing is instant access to
// music that is downloaded through the client's browser. This JavaScript
// performs checks on the visitor to validate that they hold a project 
// specific DAT that gives them access to the download. When it does, it
// enables the button(s).
//
// Inside of Metamask, you will see that the visitor will be asked to sign
// a string that looks like this:
// 'timestamp:1716507876,drmcontract:0x161e88623e775e814aC269b0B9dF5EA943a36360'"

if (document.readyState !== 'loading') {
    // already ready (edge case: second script loads very late)
    console.log('CUSTOM: NOT LOADING PATH');

    customEventHandeler();
} else {
    //dbglog('load', 'ADDED EVENT LISTENER PATH');
    console.log('CUSTOM: ADDED EVENT LISTENER PATH');
    window.addEventListener('app-initialized', customEventHandeler, { once: true });
}

// can't have this load until the page is loaded... format looks like:
async function customEventHandeler() {
    //document.addEventListener("DOMContentLoaded", async function (){
    console.log("In JavaScript custom routine");

    // to start, the user either holds this NFT or doesn't. We display different sets of data
    // and action based on this.
    console.log('HERE IS WHERE WE SHOULD SERVICE DRMAUDIO');
/*
    if (window.ethereum) {
        await window.ethereum.request({ method: 'eth_accounts' });
        window.web3 = new Web3(window.ethereum);

        let accounts = await web3.eth.getAccounts();
        // reset this if we don't already have it.
        arrGlobals['visitor'] = accounts[0];
        //g_account = accounts[0];

        if (typeof arrGlobals['visitor'] === 'undefined' || (arrGlobals['visitor'] === null)) {
            console.log('Not Connected!');
            return;
        } else {
            console.log("The Account HERE: " + arrGlobals['visitor']);
        }

        let LaContracObj = new window.web3.eth.Contract(arrGlobals['I']['IERC721']['ABI'], arrGlobals['customContract']);
        if (null == LaContracObj) {
            console.log('ER: getting customContract');
            return;
        }
        let resultCount = await LaContracObj.methods.balanceOf(arrGlobals['visitor']).call();
        console.log(resultCount);
*/
/*
        let trackCount = document.getElementById("countTracksId").innerHTML;
        console.log('trackCount: '+ trackCount);
        let startingTrack = document.getElementById("startingTracksId").innerHTML;
        console.log('startingTracksId: ' + startingTrack);

        if (resultCount > 0) {
            //console.log("Holds Custom NFT");

            for (let j = startingTrack; j <= trackCount; j++) {
                let trackDataItem = document.getElementById("trackId" + j);
                console.log("trackId: " + "trackId" + j);
                if (null != trackDataItem) {
                    trackDataItem.disabled = false;
                }
            }

        } else {
            console.log("Does not hold Custom NFT");
        }
*/
//    }

}

async function downloadTrack(_loc, _file) {
    //console.log('download: ');
    console.log('download: ' + _loc + '/' + _file);

    if (await IsCorrectNetwork()) {

        // In order to grant instant access to this visitor, they will need to sign
        // this transaction which will be decoded on the server.
        let theTimestamp = document.getElementById("customSigningTime").innerHTML;
        //console.log("time: " + theTimestamp);
        const msg = "timestamp:" + theTimestamp + ",drmcontract:" + arrGlobals['customContract']; // g_requestedContractAddr;
        //console.log(msg);

        let dataObj = document.getElementById("customTrxnId");
        dataObj.innerHTML = "";

        try {
            const from = arrGlobals['visitor'];
            //console.log(arrGlobals['visitor']);
            //const msg = `0x${Buffer.from(siweMessage, "utf8").toString("hex")}`;
            const sign = await window.ethereum // Or window.ethereum if you don't support EIP-6963. // provider
                .request({
                    method: "personal_sign",
                    params: [msg, from],
                });
            dataObj.innerHTML = "";
            //console.log("sign: "+ sign);
            //siweResult.innerHTML = sign;

            let theOrigin = window.location.origin;
            //console.log(theOrigin);
            let thePathTmp = window.location.pathname;
            //console.log(thePathTmp);
            let thePath = thePathTmp.replace("drmaudiov1/drmaudiov1", "drmaudiov1/drmaudiov1auth");
            //console.log(thePath);

            // TODO: This is the point in which we call the server to get the instant access data.
            let params1 = "signature=" + sign;
            let params2 = "address=" + arrGlobals['visitor'];
            let params3 = "timestamp=" + theTimestamp;
            let params4 = "drmcontract=" + arrGlobals['customContract']; // g_requestedContractAddr;
            let params5 = "rtype=download";
            let params6 = "loc=" + _loc;
            let params7 = "file=" + _file;
            //let params5 = "rtype=test";

            let theParams = params1 + "&" + params2 + "&" + params3 + "&" + params4 + "&" + params5 + "&" + params6 + "&" + params7;
            console.log(theParams);

            let fullURL = theOrigin + thePath + "?" + theParams;
            console.log(fullURL);

            // Here is where the code changes in order to get the blob rather than json

            fetch(fullURL, {
                method: "GET",
                headers: {
                    'Content-Type': 'audio/mp3',
                    Accept: 'audio/mp3'
                },
                mode: "cors",
                cache: "default",
            }).then(response => {
                console.log("The Fetch: ");
                console.log(response);

                //console.log("Request Headers:", response.url); // URL requested
                //console.log("Response Status:", response.status);
                //console.log("Response Content-Type:", response.headers.get("Content-Type"));

                response.blob().then(resultsblob => {

                    // For the download version, just want the results to say 'passed'.
                    console.log("Signature Results: ");
                    console.log(resultsblob);

                    const objectUrl = URL.createObjectURL(resultsblob);
                    const link = document.createElement('a');
                    link.href = objectUrl;
                    link.download = _file;
                    link.click();
                    URL.revokeObjectURL(objectUrl);
                })
            });

        } catch (error) {
            console.error(error);
            dataObj.innerHTML = error.message;
            //siweResult.innerHTML = `Error: ${error.message}`;
        }

        dataObj.style.display = "block";
    }
}
