<?php

//
// The following block of code that sets a few global variables should be included 
// in every client facing file. Files that should not be called directly should abort
// if $globalsSet is false.
//
// This file should be included in every dsn based nft. It sets the root directory
// path for both including php files and javascript files.
//
// The idea is what we want an 'theRootDir' that can be used by require_once when
// building locations to where source files exist.
//
if( !isset($globalsSet)) {
// For php, if $theRootDir doesn't exist, we create it.
if( !isset($theRootDir) ) {
	if( $_SERVER["SERVER_NAME"] == "localhost") {
		$theRootDir = $_SERVER["DOCUMENT_ROOT"].'/'.'amorstyle';
	} else {
		$theRootDir = $_SERVER["DOCUMENT_ROOT"];
	}
	//echo "base: theRootDir: ".$theRootDir."<br>";
}
// For javascript:
if( !isset($theRootURL) ) {
	$theRootURL = $_SERVER["REQUEST_SCHEME"].'://'.$_SERVER["HTTP_HOST"];
	if( $_SERVER["HTTP_HOST"] == 'localhost') {
		$theRootURL = $theRootURL.'/amorstyle';
	}
	//echo "base: theRootURL: ".$theRootURL."<br>";
}
// for project files
if( !isset($theRequestDirURL) ) {
	$theRequestDirURL = $theRootURL.pathinfo($_SERVER["PHP_SELF"],PATHINFO_DIRNAME);
	//echo 'theRequestDirURL: '.$theRequestDirURL.'<br>';
}
$globalsSet = true;
}

if( !isset($globalMobile)) {
// Are we on a mobile system or desktop pc?
$globalMobile = false;
if(strstr(strtolower($_SERVER['HTTP_USER_AGENT']), 'mobile') || strstr(strtolower($_SERVER['HTTP_USER_AGENT']), 'android')) {
	$globalMobile = true;
} 
//$globalMobile = true;
}
// for testing
if( isset($_GET['display']) && 'mobile' == $_GET['display'])
{
$globalMobile = true;
}


require_once($theRootDir.'/nfts/drmaudiov1/common.php');

require_once($theRootDir.'/dsn/url.php');
require_once($theRootDir.'/dsn/single.php');
require_once($theRootDir.'/dsn/theta.php');
require_once($theRootDir.'/dsn/dsncommon.php');
require_once($theRootDir. '/dsn/dsn.php');

/*
The Custom_nft class is designed to handle functionality that the project provides that is
above and beyond the standard IMetadataHash, ICount and IPay interfaces. 

The base code will use 'theData' to override defaults, load javascript code and callback
in order to build the custom HTML for this page.
*/
class Custom_nft {

	//private $gData = array();
	private $gName;

	//private $gSeleneNet = array();
	private $c_url = array();
	private $common;

	private $siteMD = array(); // holds global metadata
	private $md = array(); // holds project specific info

	function __construct($_c_url,$_common) {
		$this->common = $_common;
		$this->c_url = $_c_url;
	}

	public function theData() {

		$this->gName = 'drmaudiov1';

		// This array is designed to show a single project.
		$theData = array(
			'customContract' => ROOT_CONTRACT, // DRM Audio Smart Contract Address
			'javaScriptName' => $GLOBALS['theRootURL'].'/nfts/'.$this->gName.'/'.$this->gName.'.js', // fully qualified url
			'customCode' => true,
			'isSingleView' => true,
			'wProject' => 'seleneNet',
			'customTitle' => "DRM Audio Project V1"
			);

		return $theData;
	}

	//
	// This section unrolls what was found in the metadata about this project
	//
	private function customTrack($arrTracks)
	{
		$theImage = $this->md['siteURL'].$arrTracks['image'];
		$iSize = strval(76);
		$theTrackId = 'trackId'.$arrTracks['track'];

		$param1 = "'".strval($arrTracks['loc'])."'";
		$param2 = "'".strval($arrTracks['file'])."'";
		$theOnClick = 'onclick="downloadTrack('.$param1.','.$param2.')"';

		$theStr = '';
		$theStr.= '<center>';
		$theStr.= '<div style="width: 85%;margin-bottom: 15px;background-color: blue;">';

		$theStr.= '<div style="float: left;width: 33%;">';
		$theStr.= '<img  height="'.$iSize.'px" src="'.$theImage.'">'; // width="'.$iSize.'px"
		$theStr.= '</div>';

		$theStr.= '<div style="float: right;width: 66%;">';
		$theStr.= '<div style="text-align: left"><b>'.$arrTracks['title'].'</b>';
		$theStr.= '<div style="float: right" >';
		$theStr.= '<button class="natural" id="'.$theTrackId.'" '.$theOnClick.' disabled>Signature Download</button>';
		$theStr.= '</div>';
		$theStr.= '</div>';
		$theStr.= '<div style="text-align: left">'.$arrTracks['artist'].'</div>';
		$theStr.= '<div style="text-align: left">Track: '.$arrTracks['track'].'</div>';
		$theStr.= '</div>';

		$theStr.= '</div>';
		$theStr.= '</center>';
	    $theStr.= '<div style="clear: both"></div>';
		return $theStr;
	}


	private function showResource() {

		echo '<center><div id="showResource">';

		$Item = new CSingle_nft($this->md, $this->siteMD);
		echo $Item->writeDataTypes();
		$Item->centerIt();
		if( null != $Item ) {
			echo $Item->Single();
		}

		echo '</div></center>';
		echo '<div style="clear: both"></div>';
		echo '<center><div id="showResourceTrxnId" style="margin-top: 15px"></div></center>';
	}

	private function showCustom() {
	
		// let's see if we can sign something with our new class.
		$theSigningTime = time();

		$theStr = '';
		//$this->gData['theSigningTime'] = $theSigningTime;
		//$arrData = self::readJSON();
		$arrTracks = $this->md['audio']['tracks'];
		//var_dump($arrTracks[1]).'<br>';

		$theStr .= '<div id="customSigningTime" hidden>'.$theSigningTime.'</div>';
		$theStr .= '<div id="customTrxnId" hidden></div>';
		$theStr .= '<div id="startingTracksId" hidden>'.$arrTracks[0]['track'].'</div>';

		// center the title and artist
		$theStr.= '<center>';
		$theStr .= '<div class="reeltitle" >'.$this->md['audio']['title'].'</div>';
		$theStr .= '<div class="reeldesc">'.$this->md['audio']['artist'].'</div>';
		$theStr.= '</center>';

		$iCount = count($arrTracks);
		$theStr .= '<div id="countTracksId" hidden>'.$iCount.'</div>';
		for($i=0;$i<$iCount;$i++) {
			$theStr .= self::customTrack($arrTracks[$i]);
		}
		return $theStr;
	}
	//
	// This is going to be a custom sign block. The idea is that we display the "Signature Download"
	// button to the user but only enable it if the connected wallet holds at least one NFT from
	// the collection. 
	// When the user clicks the button, MetaMask is launched to sign a message. The message comes
	// from the server like a nounce. 
	// After the user signs the message, the signature is sent to the server for validation. The
	// server decodes the signature in order to get the signing account address. If it matches what
	// we expect, the server downloads the song through the client browser.
	//
	public function customHTML($_siteMD) 
	{
		// get the project metadata
		$this->siteMD = $_siteMD;
		//var_dump($this->siteMD).'<br>';

		$cDataCommon = new CCardData($this->c_url);
		if( $this->c_url->exists('p') ) {
			if( 1 == $this->c_url->value('p') ) {
				$this->md = $cDataCommon->project();
			} else if( 'hash' == $this->c_url->value('p') ){
				$this->md = $cDataCommon->hashMD();
			}
		} else if( $this->c_url->exists('t') ) {
			$this->md = $cDataCommon->token($this->c_url->value('t'));
		} 
		//var_dump($this->md).'<br>';

		$theStr = "<div class='customHTML'>";

		self::showResource();

		$theStr .= self::showCustom();

		$theStr .= "</div>";

		return $theStr;
	}
}

function run_the_code() {

	$c_url = new C_URL($_GET);
	$common = new CHelp_Common();
	$cCustomNFT = new Custom_nft($c_url,$common);

	$arrData=array();
	if($common->needHelp($c_url)) {
		$arrData = $common->help($c_url);
		if( null != $arrData ) {
			$output = json_encode($arrData,JSON_UNESCAPED_SLASHES);
			echo $output;
		}

	} else {
		$plugin = new Theta_nft($c_url);
		$plugin->Init($cCustomNFT);
		$plugin->thePage();
	}

}
run_the_code();

