<?php session_start(); ?>

<?php error_reporting(0); ?>

<?php
	//If user is not signed in redirect
	if(!$user->signed) redirect("?page=login");	

?>


<?php 

// This function validates a specific form and returns the appropriate icon
function checkValid($formid='',$all = false) {
	
	if(empty($_SESSION['sim_data'])) return false;

	if($all && !empty($_SESSION['sim_data']) ) {
		
		if ( $_SESSION['sim_data']['geom']['isvalid'] === "true" &&
			 $_SESSION['sim_data']['mat']['isvalid'] === "true" &&
			 $_SESSION['sim_data']['bdry']['isvalid'] === "true" 
//		) {return true; break;} else { return false;}  // Use in PHP5.x.x
		) {return true; } else { return false;}
			 
	} 
	
	
	return ($_SESSION['sim_data'][$formid]['isvalid'] === "true" ? "Checkmark_green.svg.png" : "X_red.png");
	
}

?>
<style>

.ui-progressbar {
    position: relative;
	margin-top: 20px;
  }
  .progress-label {
    position: absolute;
    top: 4px;
    font-weight: bold;
    text-shadow: 1px 1px 0 #fff;
	font-size:10px;
	left: 30%;
  }

</style>



<?php 
	//lets check that status of the Ec2Instance 
	//mainly we want to determine if the instance is not ready for communication and display a time 
	//estimat of when it will be to the user
	require_once("libs/cooltool/class.coolTool.php"); 
	$ctool = new coolTool($user->data['user_id']);
	
	
	if( $ctool->checkEc2Ready() === false ) {
		
		switch ($ctool->ec2State) {
			//for any of these we want to estimate the user's wait time
			case 'pending': case 'pendingssh': case 'starting-up': case 'initializing':
			
			//time difference between now and 20 minutes after ec2Launch
			$timeDiff =  strtotime("+20 minutes",strtotime($ctool->ec2StartTime)) - strtotime(date('Y-m-d H:i:s'));
			$timeDiff = ($timeDiff< 0 ? 0:$timeDiff);
			// if this is negative it means 20 minutes have gone by and yet the status is still pending ... wierd..
			if($timeDiff >= 0) {
				$waitTime = date('i:s',$timeDiff);
				$waitTimeMilliSeconds = $timeDiff*1000;
			
				echo "<script type=\"text/javascript\">$(document).ready(function(){
					$('#simulate_btn').prop('disabled',true).css('background-color', '#376E9B'); 
					var time = parseInt('{$waitTimeMilliSeconds}',10);
					function pageRefresh() {
						window.location.reload(true);	
					}
					//var myTimeoutRefreshPage = setTimeout( pageRefresh,time);
					var myTimeoutAlwaysRefreshPage = setTimeout(pageRefresh,20*1000); //refresh every 20 seconds
					var numSeconds = parseInt('{$timeDiff}',10);
					function isDigit(val) {
  						return String(+val).charAt(0) == val;
					}	
					function timer() {
						numSeconds = numSeconds - 1;
						if (numSeconds == -1) {
        					clearInterval(counter);
							//$('#simulate_btn').prop('disabled', false).css('background-color', '#00457c');
							//clearTimeout(myTimeoutRefreshPage);
							//clearTimeout(myTimeoutAlwaysRefreshPage);
							$('#warning-container').toggle(false);
        					return;
    					}
						var seconds = numSeconds % 60;
						if (isDigit(seconds)) seconds = '0'+seconds;
					
   						var minutes = Math.floor(numSeconds / 60);
    					minutes %= 60;
						$('#waitMsg').text('Your estimated wait time is ' + minutes+':'+seconds+ '.');
						$('#warning-container').toggle(true);
					}	
				
					var counter = setInterval(timer, 1000); //1000 will  run it every 1 seconds
				
					})</script>";
			
			} else {
				//20 min alapsed and still no connection. Output a new timer...

			}
			default :
			
			
		}//end switch
		//$ctool->console['errors']['cooltool'][0];
		
	} //end if
				


?>	





<script type="text/javascript">
$(document).ready(function() {
	
	var progressbar = $( "#progressbar" ),progressLabel = $( ".progress-label" );
	
	
	progressbar.toggle(false);
	var myTimeout;
	
	var queueScripts = ['bldInputFile.php','checkEc2InstanceReady.php','runCoolTool.php','processOutputFile.php'];
	var queueMessages = ['Building input file','Searching for Availible HPC Resource','Running CoolTool Solver','Processing Output'];
	var queueProgressVals = [25,50,90,100];
	
	
 
    progressbar.progressbar({
      value: false,
      change: function() {
        //progressLabel.text( progressbar.progressbar( "value" ) + "%" );
		
      },
      complete: function() {
        progressLabel.text( "Complete!" );
      }
    });
	
	function runQueueInOrder() {
    	if (queueScripts.length === 0) { 
			$('#simulate_btn').prop('disabled', false);
			progressbar.progressbar( "value", 0 );
			progressLabel.text( "" );
			progressbar.toggle(false);
			clearTimeout(myTimeout);
			$('#simulate_btn').css('background-color', '#00457c'); 
			$(location).attr('href', '?page=results');
			return; 
		}
		
    	var url = queueScripts.shift();
		var msg = queueMessages.shift();
		var pval = queueProgressVals.shift();

		console.log(url);
		console.log(msg);
		console.log(pval);
		
		progressLabel.text(msg);
		
		
    	var delay = 3;
    	$.ajax('libs/cooltool/ps/'+url, {
			type: "POST",
			async: true,
            data: {none: ''},
            dataType: "json",
			delay:delay,
			success: function(data){
				
				if(data.isError === true) {

					
					$('.uam-report').empty();
					
					$('.uam-report').append("<ul class=\"msg-error\">" + "<li>Error: "+data.Error+"</li></ul>");
					
					progressbar.progressbar( "value", 0 );
					progressLabel.text( "" );
					progressbar.toggle(false);
					clearTimeout(myTimeout);
					$('#simulate_btn').prop('disabled', false);
					$('#simulate_btn').css('background-color', '#00457c');
					
				} else {
					progressbar.progressbar( "value", pval );
					runQueueInOrder();
					
				}
				
			},
			 error: function (data) {
				console.log(data);

				console.log('an error here');
				//theError = $("<div>").html(data.responseText).find("title").text();
				//theError += " " + $("<div>").html(data.responseText).find("p").text();
				theError = $("<div>").html(data.responseText).text();


				$('.uam-report').empty();
				$('.uam-report').append("<ul class=\"msg-error\">" + "<li>Error: "+theError+"</li></ul>");
				progressbar.progressbar( "value", 0 );
				progressLabel.text( "" );
				progressbar.toggle(false);
				clearTimeout(myTimeout);	 
				$('.uam-report').toggle(true);
            }
            	
        	
    	});        
	}
	

	$('#simulate_btn').click(function() {
	
		$('.uam-report').empty();
		$(this).prop('disabled', true);
		$(this).css('background-color', '#376E9B');
		myTimeout = setTimeout( animateLabel, 500 );
		
		progressbar.toggle(true);
		progressbar.progressbar( "value", 1 );
		
		queueScripts = ['bldInputFile.php','runCoolTool.php','processOutputFile.php'];
		queueMessages = ['Building input file','Running CoolTool Solver','Processing Output'];


		queueProgressVals = [25,90,100];
		runQueueInOrder();
		
	
	});
	

	
	function animateLabel() {
		
		var array=progressLabel.text().split(".");
		var length=array.length;
		if(length == 4) {
			progressLabel.text(array[0]);
		} else {
			progressLabel.text(progressLabel.text() + ".");
			
		}
		myTimeout = setTimeout( animateLabel, 500 );
	}
	
	
	

});

</script>


<div class="subcontent">
				<div class="uam-report"></div>
                
				<h3>SIMULATE</h3>
    			<hr  class="breaklightblue" />
                <div class="leftcol">
    				<p><img id ="geom_valid_img" src="assets/images/<?php echo checkValid("geom");?>" width="60" style="vertical-align:middle"/><span class="h4">GEOMETRY</span>
    				</p>
    				<p><img id = "bdry_valid_img" src="assets/images/<?php echo checkValid("bdry");?>"  width="60" style="vertical-align:middle"/><span class="h4">Boundary Conditions</span>
                	</p>
    				<p> <img id = "mat_valid_img" src="assets/images/<?php echo checkValid("mat");?>"  width="60" style="vertical-align:middle"/><span class="h4">Materials</span>
    				</p>
    				<br />
                    <div id="warning-container" class="warning" style="display:none;">
                    	<p>The MicroCoolTool<sup>&copy;</sup> resource is loading.</p>
                        <b><p id="waitMsg">Your estimated wait time is xx.xx minutes.</p></b>
                        <p>Once the HPC resource is available, You may proceed with your simulation.</p>
                        <p>This page will auto-refresh every 20 seconds to check the state of the HPC resource. To check the status manually click <a href="?page=simulate" onclick=
                        	"window.location.reload(true);return false;">here.</a>
                        </p>
                    </div>
  					<p></p>
            </div><!-- End .leftcol -->
            <div class = "rightcol">
            
            <img alt="Cold Plate Simulation" src="assets/images/simulate.png" width="350"/>
            <div id="progressbar"><div class="progress-label">Loading...</div></div>
            <p style="float:right;">
                    	<input onclick="window.location.href='?page=mat';" type="button"  value="BACK" style="width: 
                        	120px; height: 70px; -webkit-appearance: none; background-color:#00457c; font-weight:bold; 
                            font-size:18px; color:#adafb2; margin-top:20px; margin-bottom:20px; margin-right:10px; display
                            : inline;" /> 
                    	<input name="simulate" type="submit" id="simulate_btn" value="SIMULATE" style="width: 
                        	120px; height: 70px; -webkit-appearance: none; background-color:#00457c; font-weight:bold; 
                            font-size:18px; color:#adafb2; margin-top:20px; margin-bottom:20px; margin-right:10px;  
                            display:<?php echo (checkValid('',true)  === true ? "inline" : "none");?>;" />
            </p> 
            </div><!-- End .rightcol -->
 <?php //checkValid('',true); ?>           
            
</div><!-- end .subcontent -->     
            