<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content-type="text/html; charset=utf-8" />
<script src="../JS/jquery-1.7.1.min.js"></script>
<link rel='stylesheet' type='text/css' href='../CSS/Buttons.css'>

<!-- Code to inform user that database has been updated -->
<script>
	function customAlert(msg,duration){
		var styler = document.createElement('div');
		styler.setAttribute('style','position:absolute; left:0px; top:0px; z-index:100; border: solid 20px white;width:560;height:100;background-color:white;color:Silver');
		styler.innerHTML = '<h3>'+msg+'</h3>';
		setTimeout(function(){styler.parentNode.removeChild(styler);},duration);
		document.body.appendChild(styler);
	}
	function caller(){
		customAlert('EnTrak database updated to latest version &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;','2000');
	}
</script>
</head>
<body <?php if($_GET[updated] == "yes"){
 $msg_delivered = true; echo("onload='caller()'");} ?> >

<?php
if($_GET['refresh'] == true)echo ("<script>parent.window.location.reload('../Projects.html')</script>");
?>

<a href="../Index.html" target="_top"> 		<button title="Introduction to EnTrak" type="button">Introduction</button>  	</a>
<a href="../Projects.html" target="_top"> 	<button title="Define descriptive and time series attributes and start data collection" type="button" style="border-style:inset;">Data Definition</button>  	</a> <!-- PROJECTS -->
<a href="../Setup_ES.html" target="_top"> 	<button title="Define services to be run on the data" type="button">Service Definition</button>  </a> <!-- EService setup-->
<a href="../ESView.html" target="_top"> 	<button title="Run services" type="button">Service Management</button>  </a> <!--EService launch -->
<br/>

<!-- Read projects in ProjectsList.csv and display in drop down -->
<form action="TopWithDropDown.html" method="post">
<select name="DBdropdown" style="width:90%;	max-width: 600px;" onchange="$('#load').trigger('click');">

<?php
require '../2_Projects/FileOperations.php';
$lineA = array();
$handle = fopen("../ProjectsList.csv","r")or die("Unable to open ../ProjectsList.csv file!");
$selectedDB=$_POST[DBdropdown];

// if user selected default entry (select DB) then close current DB
if($selectedDB == "0"){
	DeleteCurrentlyOpenedDBName();
	echo ("<script>parent.window.location.reload('../Projects.html')</script>");
}
$curDB = "../CurrentlyOpenedDBName.tmp";
if(file_exists ($curDB)){
	$f = fopen($curDB, "r");
	$selectedDB   = trim(fgets($f)); // linked database name
	fclose($f);
}

if($selectedDB == NULL)$selectedDB=$_GET[DB];
if($selectedDB == NULL){
	echo ("<option value='0' selected> &nbsp &nbsp Select project </option>");
}else{
	echo ("<option value='0'> &nbsp &nbsp Select project </option>");
}

while ($line = fgets($handle)){
	if($line[0] == "#"){
		// do nothing this is a comment
	}else{
		$selected = "";
		$lineA = explode("!",$line);
		$dbName = trim($lineA[0]);
		if($dbName == $selectedDB)$selected = "selected";
		$dbNameLen = strlen($dbName);
		$dbDesc = substr($line,$dbNameLen + 1);
		$dbDesc = trim($dbDesc);

		// Remove (un)locked and # from end of descriptive string
		$dbDesc = preg_replace('/locked$/' ,'',$dbDesc);
		$dbDesc = preg_replace('/un$/'     ,'',$dbDesc);
		$dbDesc = preg_replace('/!$/'      ,'',$dbDesc);
		$dbStatus = trim($lineA[2]); // locked or unlocked
		if($dbStatus == "locked"){
			echo ("<option value='{$dbName}' {$selected}>"."&#x1f512; "." {$dbDesc} </option>");
		}else{
			echo ("<option value='{$dbName}' {$selected}>"."&#x1f513; "." {$dbDesc} </option>");
		}
	}
}
?>
</select>
<button class="btnAdd" type="submit" name= "NewDB" formaction="../2_Projects/MakeNewDatabase.html?DB=make_new_db" target="TopFrame">+</button>

<!-- make hidden button -->
<button type="submit" name= "SelectDB" id = "load" style="color: transparent; background-color: transparent; border-color: transparent; cursor: default;"></button>
</form>

<?php
//require '../2_Projects/FileOperations.php';

// Open existing database
if(isset($_POST[SelectDB])){

	if($_POST[DBdropdown] == "0")return;

	//echo "opening " . $_POST[DBdropdown];
	$name = $_POST[DBdropdown];
	if(DBNotExistsAlready($name)){
		WarnUser("Database by that name does not exist or is locked","../Common/TopWithDropDown.html?DBNotXST=1");
		exit;
	}

	// Check if older version database
	mysql_select_db($name, $con);
	$updated = false;

	// If table named ENTITY exists it is oldest database version supported, no version number available
	// Delete this table and put in HighLevInfo table
	$db_version = 0;
	if(mysql_num_rows(mysql_query("SHOW TABLES LIKE 'Entity'",$con))==1){
		$db_version = 0;
	}else{
		$res = mysql_query("SELECT max(db_version) FROM HighLevInfo",$con);
		while($row = mysql_fetch_array($res))$db_version = $row[0];
	}

	$smaStr = 60;
	if($db_version < 1){
		$db_version = 1;
		mysql_query("DROP TABLE IF EXISTS Entity",$con);
		mysql_query("CREATE TABLE HighLevInfo(
						db_version INT,
						name VARCHAR(60)
						);",$con);
		mysql_query("INSERT INTO HighLevInfo (db_version) VALUES (1)",$con); // DB version to only increment in integers

		// Change frequency table
		// Uncomment following line when times_per_period is changed to a more sensible name e.g. time_period
		//mysql_query("ALTER TABLE Frequency CHANGE times_per_period modifier VARCHAR({$smaStr})",$con);
		mysql_query("ALTER TABLE Frequency
					ADD sta_tm_day VARCHAR({$smaStr}),
					ADD end_tm_day VARCHAR({$smaStr}),
					ADD day_o_week VARCHAR({$smaStr}),
					ADD day_o_mnth VARCHAR({$smaStr})
						",$con);

		// Update db_version
		$updated = true;
	}

	if($db_version < 2){
		$db_version = 2;
		mysql_query("INSERT INTO HighLevInfo (db_version) VALUES (2)",$con); // DB version to only increment in integers

		// Make changes
		mysql_query("ALTER TABLE Output ADD es_data_freq_id INT",$con);
		mysql_query("ALTER TABLE Output ADD FOREIGN KEY (es_data_freq_id) REFERENCES Frequency(frequency_id)",$con);

		// Update db_version
		$updated = true;
	}

	if($db_version < 3){
		$db_version = 3;
		mysql_query("INSERT INTO HighLevInfo (db_version) VALUES (3)",$con); // DB version to only increment in integers

		// Make changes
		mysql_query("ALTER TABLE Fetcher ADD expected_data_items INT",$con);

		// Update db_version
		$updated = true;
	}

	// Add fetch_status (toggle whether DID is to be fetched or not when the start button is pressed)
	if($db_version < 4){
		$db_version = 4;
		mysql_query("INSERT INTO HighLevInfo (db_version) VALUES (4)",$con); // DB version to only increment in integers

		// Make changes
		mysql_query("ALTER TABLE Dynamic ADD fetch_status VARCHAR(60)",$con);

		// Update db_version
		$updated = true;
	}

	// Add Dynamic.MDF_status (Whether fetching is to be made individually for this DID or using MDF)
	if($db_version < 5){
		$db_version = 5;
		mysql_query("INSERT INTO HighLevInfo (db_version) VALUES (5)",$con); // DB version to only increment in integers

		// Make changes
		mysql_query("ALTER TABLE Dynamic ADD MDF_status VARCHAR(20)",$con);

		// Update db_version
		$updated = true;
	}

	// Add MDF tag to HighLevInfo
	if($db_version < 6){
		$db_version = 6;
		mysql_query("INSERT INTO HighLevInfo (db_version) VALUES (6)",$con); // DB version to only increment in integers

		// Make changes
		mysql_query("ALTER TABLE HighLevInfo ADD value VARCHAR(3)",$con);
		mysql_query("INSERT INTO HighLevInfo(name) VALUES('MDF (yes or )')",$con);

		// Update db_version
		$updated = true;
	}

	// Add MDF tag to HighLevInfo
	if($db_version < 7){
		$db_version = 7;
		mysql_query("INSERT INTO HighLevInfo (db_version) VALUES (7)",$con); // DB version to only increment in integers

		// Make changes
		mysql_query("INSERT INTO HighLevInfo(name) VALUES('MDF_status (fet or not)')",$con);

		// Update db_version
		$updated = true;
	}

	// More DB updates can go here
	if($db_version < 8){

		// Make changes

		// Update db_version

	}

	// Inform user that version number has been updated
	//if($updated)echo ("<script> alert('Database updated to version {$db_version}');</script>");
	if($updated){
		$updated = "yes";
	}else{
		$updated = "no";
	}

	SelectDB($name); // write DB name to CurrentlyOpenedDBName.tmp
	mysql_close();

	// Reload Projects.html in parent frame
	echo ("<a id='#OpenDB' href='../Projects.html?DB={$_POST[DBdropdown]}&updated={$updated}' ' target='_parent'></a> ");
	echo("<script>document.getElementById('#OpenDB').click();</script>");
}


?>
</body>
</html>
