<?php
include_once '../auth.php';
?>
<html>
<head>
    <link rel="stylesheet" href="../script/tocas/tocas.css">
	<script src="../script/tocas/tocas.js"></script>
	<script src="../script/jquery.min.js"></script>
	<script src="../script/ao_module.js"></script>
</head>
<body>
	<div class="ts container">
	<br>
	<div class="ts segment">
		<div class="ts header">
			<i class="file icon"></i>
			<div class="content">
				arozdfs Demo Module
				<div class="sub header">Reference code for how to use the arozdfs sybsystem</div>
			</div>
		</div>
	</div>
	<?php 
	//Check if arozdfs services exists.
	if (!file_exists("../SystemAOB/functions/arozdfs/")){
		die("ERROR. Arozdfs service not found or permission denied.");
	}
	$dfsroot = "../SystemAOB/functions/arozdfs/";
	$settings = json_decode(file_get_contents($dfsroot . "clusterSetting.config"),true);
	$uploadTargets = explode("\n",trim(file_get_contents($dfsroot . "remoteDisks.config")));
	$storeDir = file_get_contents($dfsroot . "storageDirectory.config");
	$parentDir = dirname(__FILE__);
	?>
	<div class="ts primary segment">
	<p>There are five main functions in using arozdfs. Select the following functions one by one and try out the process.</p>
		<div class="ts breadcrumb">
			<a class="section">Upload</a>
			<i class="right chevron icon divider"></i>
			<a class="section">Slice</a>
			<i class="right chevron icon divider"></i>
			<a class="section">Download</a>
			<i class="right chevron icon divider"></i>
			<a class="section">Open</a>
			<i class="right chevron icon divider"></i>
			<a class="section">Remove</a>
		</div>
	</div>
	<div class="ts segment">
		<p>1. Upload the file that you want to send into the arozdfs. Click <a href="">here</a> after the upload is finished.</p>
		<?php $moduleName =  basename($parentDir); ?>
		<iframe width="100%" height="260px" src="../Upload%20Manager/upload_interface_min.php?target=SystemAOB\functions\arozdfs&filetype="> </iframe>
	</div>
	<div class="ts segment">
		<p>2. Select the file you want slice and click on it. The page will refresh automatically when slicing processes ended.</p>
		<div class="ts ordered list">
			<?php
				$uploadedFiles = glob($dfsroot . "uploads/*");
				foreach ($uploadedFiles as $file){
					if (is_file($file)){
						echo '<a class="item hexfoldername" rawname="' . basename($file) . '" onClick="sliceThis(this);">' . basename($file) .'</a>';
					}
				}
				?>
		</div>
        <div class="ts horizontal form">
            <div class="field">
                <label>Chunk Size (MB)</label>
                <input id="chunksize" type="number" value="32">
            </div>
        </div>
	</div>
	<div class="ts segment">
		<p>3. Upload the chunks to the listed clusters. If nothing is displayed below, please redo step 2 until the file chunks are shown below.<br>Upload pending chunk: </p>
		<div class="ts ordered list">
			<?php
			    $valid = false;
				if (isset($_GET['uuid'])){
				    $valid = true;
					$chunks = glob($dfsroot . "chunks/" . $_GET['uuid'] . "/" . $_GET['uuid'] . "*");
					foreach ($chunks as $chunk){
						if (is_file($chunk)){
							echo '<a class="item">' . basename($chunk) . '</a>';
						}
					}
			
				}
				
			?>
		</div>
		<div class="ts horizontal form">
            <div class="field">
                <label>Storage Filename</label>
                <input type="text" value="<?php 
                    if (isset($_GET['filename'])){
                        echo strip_tags($_GET['filename']);
                    }
                ?>">
            </div>
        </div>
        <?php
            //Echo the upload button if uuid and filename is given
            if ($valid){
                echo '<button class="ts primary button" filename="' . strip_tags($_GET['filename']) . '" uuid="' . $_GET['uuid'] . '" onClick="startUpload(this);">Upload</button>';
            }
        ?>
	</div>
	<div class="ts segment">
        <p>4. Download and Merge: These are the files uploaded to the arozdfs clusters. Click any of the filename below to download.</p>
        <div class="ts ordered list">
            <?php
                $fileIndexs = glob($dfsroot . "index/*.index");
                foreach ($fileIndexs as $index){
                    echo '<a class="item hexfoldername" rawname="' . basename($index,".index") . '" onclick="downloadFile(this);" >' . basename($index,".index") . '</a>';
                }
            ?>
        </div>
	</div>
    <div class="ts segment">
        <p>5. Preview exported files. Click any file in the list below to view its content.</p>
        <div class="ts ordered list">
            <?php
                $mergedFiles = glob($dfsroot . "tmp/outfiles/*");
                foreach ($mergedFiles as $file){
                    if (is_file($file)){
                         echo '<a class="item hexfoldername" filename="' . $file. '" onclick="openFile(this);" >' . basename($file) . '</a>';
                    }
                   
                }
            ?>
        </div>
    </div>
	<div class="ts primary segment">
		<p>Here is the file index tree that is currently stored inside the distrubuted file system.</p>
		<div class="ts ordered list">
		<?php
		
		function getDirContents($path) {
			$rii = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path));

			$files = array(); 
			foreach ($rii as $file)
				if (!$file->isDir())
					$files[] = $file->getPathname();

			return $files;
		}
		
		
		foreach (getDirContents($dfsroot . trim("index/")) as $index){
			echo '<div class="item">' . str_replace("\\","/",str_replace($dfsroot,"arozdfs//",$index)) . '</div>'; //Fix the problem on Window host which display a mix of / and \
		}
		?>
		</div>
		<p>Here is a list of chunks stored on this host.</p>
		<div class="ts ordered list">
			<?php
			$realStorePath = $storeDir;
			if (file_exists($dfsroot . trim($storeDir))){
				$realStorePath = $dfsroot . trim($storeDir);
			}
			foreach (getDirContents($realStorePath) as $index){
				echo '<div class="item">' . str_replace("\\","/",str_replace($dfsroot,"arozdfs//",$index)) . '</div>'; 
			}
			?>
		</div>
	</div>
	<div class="ts primary segment">
		<p>The followings are "arozdfs root", "cluster setting", "upload target UUID" and "local storage directory" information.<br>
			These can be modified using NotepadA before the upload process start.</p>
			<?php
			var_dump([$dfsroot,$settings,$uploadTargets,$storeDir]);
			?>
	</div>

	<div id="msgbox" class="ts active bottom right snackbar" style="display:none;">
		<div id="message" class="content">
			This is a message box.
		</div>
	</div>

	</div>
<script>
var arozdfsModule = "../ArOZDFS/"; //Current module path from ArOZ Online Root

$(document).ready(function(){
	//Translate all the hex foldername to human readable filename if found
	$(".hexfoldername").each(function(){
		var decodedName = ao_module_codec.decodeUmFilename($(this).text()); //Decode the umfile naming method.
		$(this).text(decodedName); //Upload the hex filename to its original filename
	});
});

function baseName(str){
   var tmp = str.split("/");
   return tmp.pop();
}

function openFile(object){
    var filename = $(object).attr("filename");
    var displayname = ao_module_codec.decodeUmFilename(baseName(filename));
    if (ao_module_virtualDesktop){
        ao_module_openFile(filename.replace("../",""),displayname);
    }else{
        window.open("../SystemAOB/functions/file_system/index.php?controlLv=2&mode=file&dir=" + filename.replace("../","") + "&filename=" + displayname);
    }
}

function downloadFile(object){
    var vdir = $(object).attr("rawname");
    msgbox("Download started. This might take a while.");
	$.get("../SystemAOB/functions/arozdfs/requestFromCluster.php?vdir=" + vdir.trim(),function(data){
        console.log(data);
        mergeFileChunks(data.trim(),vdir);
	});
}

function mergeFileChunks(chunkid, outfilename){
    msgbox("Merging process started.");
	$.get("../SystemAOB/functions/arozdfs/mergeFileChunks.php?chunkid=" + chunkid + "&outfile=" + outfilename ,function(data){
        console.log(data);
        if (data.includes("DONE")){
            window.location.reload();
        }
	});
}


function startUpload(object){
	var uuid = $(object).attr("uuid");
	var vdir = $(object).attr("filename");
	msgbox("Upload started. This might take a while.");
	$.get("../SystemAOB/functions/arozdfs/uploadToCluster.php?uuid=" + uuid.trim() + "&filename=" + vdir.trim(),function(data){
	    console.log(data);
	    if (data.includes("[OK] All chunks uploaded")){
	        window.location.reload();
	    }
	});
}

function sliceThis(object){
	var filename = $(object).attr("rawname"); //Get the original name from the DOM attibute
	$.get("../SystemAOB/functions/arozdfs/slice.php?filename=" + filename + "&chunksize=" + $("#chunksize").val(),function(data){
		//After slicing, an UUID should return. The sliced file chunks are now lying inside arozdfs/chunks/{uuid}/{uuid}_* 
		console.log(data);
		window.location.href = "index.php?uuid=" + data + "&filename=" + filename;
	});
}


function msgbox(msg){
//Just a utility function to show that something is working
	$("#message").text(msg);
	$("#msgbox").fadeIn().delay(5000).fadeOut();
}
</script>
</body>
</html>