<?php

	include('correlation.php');
	include('chessmaster.php');
	
	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);	
	
	// 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";
	
	
	$date_ajout = $timestamp_ajout = mktime (0, 0, 0, $mois, $jour, $annee); 
	
	$donnees = array();
	$donnees[0] = $date_ajout;
	$donnees[1] = "fabien";
	$donnees[2] = "stephaner";
	$donnees[3] = "1";
	$donnees[4] = "0";
	
	$last_timestamp = end($game);
	
	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);
		
		algo_elo($donnees, "nostatistique", "sql", 0);
			
		$sql = "SELECT * FROM chessmaster";
		$results = mysql_query($sql);
		$n =  mysql_num_rows($results);
		$sql = "SELECT * FROM chessmaster WHERE id = '$n' ";
		$results = mysql_query($sql);
		$row = mysql_fetch_assoc($results);
		$master = $row['gagnant'];
		
		$J1 = $donnees[1];
		$J2 = $donnees[2];
		$whiteScore = $donnees[3];
		$blackScore = $donnees[4];
		
		if($J1 == $master &&  $J2 != $master)
		{
			if($whiteScore == 1)
			{
				insert_chessmaster_DB($J1, $J2, $J1, $date_ajout);
				//echo 1;
			}
			if($whiteScore == 0 )
			{
				insert_chessmaster_DB($J1, $J2, $J2, $date_ajout);
				//echo 2;
			}
			if($whiteScore == 0.5 && $blackScore == 0.5)
			{
				insert_chessmaster_DB($J1, $J2, $J1, $date_ajout);
				//echo 3;
			}
		
		}	
		
		if($J1 != $master &&  $J2 == $master)
		{
			if($blackScore == 1)
			{
				//echo 4;
				insert_chessmaster_DB($J1, $J2, $J2, $date_ajout);
			}
			if($blackScore == 0)
			{
				//echo 5;
				insert_chessmaster_DB($J1, $J2, $J1, $date_ajout);
			}
			if($whiteScore == 0.5 && $blackScore == 0.5)
			{
				//echo 6;
				insert_chessmaster_DB($J1, $J2, $J2, $date_ajout);
			}
		}	

		echo "Ajout à la suite...";
		
	}
	
	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>";
		
		regenerer($tab_global);

	}		
	
function regenerer_DB($tab_global)
{	
		// 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 =  0;	
		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;
			chess_master($donnees,$indice);
		}
					
		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");	
					}
				}	
			}	
}		
	
?>
