<?php

	//include('database.php');
	include('correlation.php');
	DB_connexion(); 

	date_default_timezone_set('Europe/Paris');
	
	$sql = "SELECT * FROM parties";
	$results = mysql_query($sql);
	
	while($row = mysql_fetch_assoc($results))
	{
		$game[] = intval($row["date"]);
	}

	echo "<pre>";
	//print_r($game);	
	
	$last_timestamp = end($game);
	
	// ok
	$mois = "11";
	$jour = "15";
	$annee = "2015";
							
	// ok
	//$mois = "03";
	//$jour = "05";
	//$annee = "2015";
	
	// ok
	//$mois = "11";
	//$jour = "04";
	//$annee = "2015";

	// ok
	//$mois = "11";
	//$jour = "07";
	//$annee = "2015";
	
	
	// ok
	//$mois = "11";
	//$jour = "08";
	//$annee = "2015";
	
	// ok
	//$mois = "11";
	//$jour = "01";
	//$annee = "2015";
	
	//ok
	//$mois = "10";
	//$jour = "31";
	//$annee = "2015";
	
	// ok
	//$mois = "11";
	//$jour = "03";
	//$annee = "2015";
	
	$donnees = array();
	$donnees[0] = $jour ."/" .$mois ."/" .$annee; 
	$donnees[1] = "coco";
	$donnees[2] = "glandu";
	$donnees[3] = "20";
	$donnees[4] = "8";
	
	$date_ajout = $timestamp_ajout = mktime (0, 0, 0, $mois, $jour, $annee); //31 -> 4  30 -> 1  28 -> 0 29 -> 0
	
	echo $last_timestamp ."  " .$date_ajout;
	
	if($date_ajout > $last_timestamp)
	{
		$tmp = transfert_DB();
	
		$nb_parties = $tmp[0];
		$table_fichier = $tmp[1];
		
		$table[] = $donnees;
		$tab_global = array_merge($table_fichier,$table);
		print_r($tab_global);
							
		echo "<br>";
		echo "**********************";		
		echo "<br>";
		
	}
	
	else
	{
		// recherche si la date existe ?

		$test =  array_search( $date_ajout , $game); // retourne la cle si elle existe
	
		if($test != "")
		{
			echo "Timestamp existe...";
				
			echo "Ce que je recherche -> " .$mois ." " .$jour ." " .$annee ."     " .$date_ajout;
			echo "<br>";
			echo "Position " .$test;
			echo "<br>";
			echo $game[$test];
			$array = array_count_values($game);
			$nb_partie = $array[$date_ajout];
			echo "<br>";
			echo $nb_partie;
			echo "<br>";
			$index_ajout =  $test + $nb_partie - 1;
			echo $index_ajout;
		}
	
		else
		{
			echo "Timestamp au plus proche...";
			
			// on fait un recherche pour trouver le timestamp le plus proche
			$num= $date_ajout; 
			$diff=$num;
			$min=$num;

			foreach($game as $a)
			{
			  if( abs($a-$num)< $diff )
			  {
				  $diff=abs($a-$num);
				  $min=$a;
			  }
			}
	
			echo "Ce que je recherche -> " .$mois ." " .$jour ." " .$annee ."     " .$date_ajout;
			// pour le 28 mars 2015 1427497200	
			echo "<br>";
			echo "Ce que je trouve ->" .$min;
			echo "<br>";
			echo "La date :" .date('d/m/Y', $min);
		
			$test =  array_search( $min , $game);
			echo "<br>";
			echo "Position " .$test;
			$array = array_count_values($game);
			$nb_partie = $array[$min];
			echo "<br>";
			echo $nb_partie;
			echo "<br>";
		
			$diff = $date_ajout-$min;
			echo $diff;
			
			// avant 
			if($date_ajout < $min)
			{
				$index_ajout =  $test - 1 ;
				echo $index_ajout;
			}
			// apres
			if($date_ajout > $min)
			{
				$index_ajout =  $test  ;
				echo $index_ajout;
				
			}
			echo "<br>";
			echo "<br>";
		}
		
		$tmp = transfert_DB();
		$nb_parties = $tmp[0];
		$table_fichier = $tmp[1];

		$tab1 = array();
		$tab2 = array();

		for ($i=0; $i <= $index_ajout ; $i++)
		{
			$tab1[] = $table_fichier[$i];
		}
							
		for ($i=$index_ajout + 1 ; $i < $nb_parties; $i++)
		{
			$tab2[] = $table_fichier[$i];
		}
							
		echo "------------------TABLE------------------------<br>";
		print_r($table_fichier);	
		echo "-----------------------------------------------<br>";

		echo "------------------TAB 1------------------------<br>";
		print_r($tab1);	
		echo "-----------------------------------------------<br>";
														
		print_r($donnees);	
		echo "------------------TAB 2------------------------<br>";		
		print_r($tab2);			
		echo "-----------------------------------------------<br>";

		$table[] = $donnees;
		$tab_global = array_merge($tab1,$table, $tab2);
		print_r($tab_global);
							
		echo "<br>";
		echo "**********************";		
		echo "<br>";
							
		// insertion donc on recalcul l'ensemble de la table_csv
							
		/*$fp = fopen($nom_fichier, 'w'); 
								
		for ($i=0; $i < count($tab_global); $i++)
		{
			$str_comma_separated = implode(";", $tab_global[$i]);
			fputs ($fp, $str_comma_separated);

			if($i != count($tab_global) - 1)
			{
				fputs($fp, "\n");
			}
		}

		fclose($fp);*/
							
		// joueur
					
		$joueur = array();
		$sql = "SELECT * FROM classement ORDER by joueur asc"; 
		$results = mysql_query($sql);
								
		while($row = mysql_fetch_assoc($results))
		{
			$joueur[] = $row['joueur'];
		}

		// regenerer le classement
		mysql_query('TRUNCATE TABLE classement;');
		mysql_query('TRUNCATE TABLE evolution;');
		mysql_query('TRUNCATE TABLE parties;');
		mysql_query('TRUNCATE TABLE chessmaster;');
	
		stockage_joueurs_DB($joueur);
		
		$indice =  1;	
		for ($i=0; $i < count($tab_global); $i++)
		{
			$datas = $tab_global[$i];
			list($jour, $mois, $annee) = explode('/', $datas[0]);
			$timestamp = mktime (0, 0, 0, $mois, $jour, $annee);
			$donnees[0] = $timestamp; 
			$donnees[1] = $datas[1];
			$donnees[2] = $datas[2];
			$donnees[3] = $datas[3];
			$donnees[4] = $datas[4];
			algo_elo($donnees, "nostatistique", "sql", $indice );
			$indice = $indice + 1;
		}
		

/*		$file = fopen ("new_insertion.txt","r");
		
		$indice =  1;	
		while(! feof($file))
		{
			$tmp = fgets($file);
			$tmp = strtolower($tmp);
			$pieces = explode(";", $tmp);
			$donnees[0] = $pieces[0];
			list($jour, $mois, $annee) = explode('/', $donnees[0]);
			$timestamp = mktime (0, 0, 0, $mois, $jour, $annee);
			$donnees[0] = $timestamp; 
			$donnees[1] = $pieces[1];
			$donnees[2] = $pieces[2];
			$donnees[3] = $pieces[3];
			$donnees[4] = $pieces[4];
			algo_elo($donnees, "nostatistique", "sql", $indice );
			$indice = $indice + 1;
		}
					
		echo "Insertion: Fin ";
*/							

	}		
		
function transfert_DB()
{	
		$sql = "SELECT * FROM parties ORDER by date asc"; 
		$results = mysql_query($sql);
		$nb_parties = mysql_num_rows($results);

		while($row = mysql_fetch_assoc($results))
		{
			$blanc = $row['w_name'];
			$noir = $row['b_name'];
			$date = $row['date'];
			$resultat = $row['result'];
			$date_partie = date('d/m/Y', $date);

			if($resultat == 1)
			{
				$_score_blanc = 1;
				$_score_noir = 0;
			}
			if($resultat == 2)
			{
				$_score_blanc = 0;
				$_score_noir = 1;
			}
			if($resultat == 3)
			{
				$_score_blanc = 0.5;
				$_score_noir = 0.5;
			}

			$table_csv[0] = $date_partie;
			$table_csv[1] = $blanc;
			$table_csv[2] = $noir;
			$table_csv[3] = $_score_blanc;
			$table_csv[4] = $_score_noir;
			$table_fichier[] = $table_csv;
		}
	
		$nom_fichier = "sauvegarde_insertion.txt";

		$fp = fopen($nom_fichier, 'w'); 

		for ($i=0; $i < $nb_parties; $i++)
		{
			$str_comma_separated = implode(";", $table_fichier[$i]);
			fputs ($fp, $str_comma_separated);
			if($i != $nb_parties - 1)
				fputs($fp, "\n");
		}

		fclose($fp);
		
		$retour[] = $nb_parties;
		$retour[] = $table_fichier;
		return($retour);
}
		
function stockage_joueurs_DB($donnees)
{
			$elo = 1000;
			$nb_ligne =  count($donnees);
			
			for ($i=0; $i < $nb_ligne; $i++)
			{
				$prenom = $donnees[$i];
				$partie = 0;
				$prior = 0;
				// verifier que le joueur n'existe pas dans la database
				$sql = "select joueur from classement where joueur = '$prenom' ";
				$result = mysql_query($sql);
				if(mysql_num_rows($result)>=1)
				{
						echo "Ce joueur existe dÃ©jÃ  :" .$prenom;
						echo "<br>";
				}
		
				else
				{
					$sql = "SELECT elo FROM elo_affectation WHERE joueur ='".$prenom."'";
					$result = mysql_query($sql);
					$row = mysql_fetch_array($result);
					$elo =  $row['elo'];
			
					$sql = " INSERT INTO classement ";
					$sql = $sql . " (joueur, elo, parties, prior, initial) VALUES ";
					$sql = $sql . " ('$prenom', '$elo','$partie','$prior', '$elo') ";
					//echo $sql;
					//echo "<br>";
					$result = mysql_query($sql);
					if (!$result)
					{ 
						echo("ERROR: " . mysql_error() . "\n$SQL\n");	
					}
				}	
			}	
}		
	
?>
