<?php
/*
 * This file contains a mini function library used for DB purposes.
 * 
 * Author : Brett
 */


/**
 * This function parses the folder ranking and adds every entry in the MySQL Database.
 * the ranking folder contains the ladder for every chosen instance of the Renault Challenge.
 * If no solution has been found by a candidate, the DB is still updated with -1 as constraint scores / mark.
 * It fills up to ~400 entries (for 2005 competition).
 */

function parse_rankings()
{ 
  try
    {

      // The following condition secures a bit the table filling : it waits for a GET parameter phaseX=true to execute the code. 
      if(isset($_GET['phaseX']) AND $_GET['phaseX']=='true')
	{    
	  $requete= $bdd->query('SELECT instance_name FROM InstancesX');
	  $instances = array();
	  while($donnees = $requete->fetch())
	    array_push($instances,$donnees['instance_name']);

	  $dir = new DirectoryIterator(dirname('/home/roadef/www/2005/model/ranking/.'));
	  foreach ($instances as $fileinfo)
	    {
	      $reqidinstance = $bdd->prepare('SELECT id_instance FROM InstancesX WHERE instance_name=:inst');
	      $reqidinstance->execute(array('inst'=>$fileinfo));
	      $f_idinstance = $reqidinstance->fetch();
	      $idinstance = $f_idinstance['id_instance'];
	      echo $fileinfo . '<b>(' . $idinstance . ')</b><br />';
	      $currentFile = fopen('/home/roadef/www/2005/model/ranking/' . $fileinfo . '.txt','r');
	      if($currentFile)
		{
		  $currentLine = fgets($currentFile);
		  while(($currentLine = fgets($currentFile)) !== false)
		    {
		      if($currentLine !== '')
			{
			  $rank = strtok($currentLine, ';');
			  $candidate = strtok(';');
			  $candidate = trim($candidate);
			  $reqidcandidate = $bdd->prepare('SELECT id FROM Candidates2005 WHERE candidate_name=:candi');
			  $reqidcandidate->execute(array('candi'=>$candidate));
			  $f_idcandidate = $reqidcandidate->fetch();
			  $idcandidate = $f_idcandidate['id'];
			  $hprc = strtok('; ');
			  if(strcmp($hprc, 'no')!==0)
			    {
			      strtok('; ');
			      $lprc = strtok('; ');
			      strtok('; ');
			      $pcc =  strtok('; ');
			      strtok('; ');
			      $mark =  strtok('; ');
			      echo '<b>Adding ' . $candidate . '(' . $idcandidate . ')</b> : ' . $hprc . ' ' . $lprc . ' ' . $pcc . ' = ' . $mark . '...<br />';
			      $request = $bdd->prepare('INSERT INTO Solutions2005(`numInstance`, `numCandidate`, `HPRC`, `LPRC`, `PCC`, `mark`, `rank`) VALUES(:instance, :candidate, :hp, :lp, :pc, :ma, :ra)');
			      $request->execute(array(
						      'instance'=>$idinstance,
						      'candidate'=>$idcandidate,
						      'hp'=>$hprc,
						      'lp'=>$lprc,
						      'pc'=>$pcc,
						      'ma'=>$mark,
						      'ra'=>$rank));
			    }
			  else
			    {
			      $request = $bdd->prepare('INSERT INTO Solutions2005(`numInstance`, `numCandidate`, `HPRC`, `LPRC`, `PCC`, `mark`, `rank`) VALUES(:instance, :candidate, -1, -1, -1, -1, :ra)');
			      $request->execute(array(
						      'instance'=>$idinstance,
						      'candidate'=>$idcandidate,
						      'ra'=>$rank));
			      echo '<b>Added  <span style="color:red">DEFAULT</span> ' . $candidate . '(' . $idcandidate . ')</b> : ' . $hprc . ' ' . $lprc . ' ' . $pcc . ' = ' . $mark . '<br />';
			    }
																		     
			}
		    }
		}
	      else
		{
		  echo 'Couldn\' parse this file ! <br />';
		}
	      fclose($currentFile);
	      echo '<hr /><br /><br />';
	    }
	}
    }
  catch (Exception $e)
    {
      die('Erreur : ' . $e->getMessage());
    }
}

/*
 * Deprecated since implementation of objects
 */
function getSolutionsOfCandidate($candidate)
{
  $bdd = new PDO('mysql:host=localhost;dbname=roadef;charset=utf8', 'roadef', 'dptinforoadef', array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
  $req = $bdd->prepare('SELECT * FROM Candidates2005 c, InstancesX i, Solutions2005 s WHERE c.id=s.numCandidate AND i.id_instance=s.numInstance AND candidate_name=:candi');
  $req->execute(array('candi'=>$candidate));
  if($req->rowCount()>0)
    {
      echo '<b>' . $candidate . '</b><br />';
      while($result = $req->fetch())
	{
	  echo $result['instance_name'] . ' : ' .$result['mark'] . '<br />';
	}
    }
  else
    echo 'No result... <br />';

}

function computeAverageForAllInstances()
{
  include_once('../model/classes/Challenge2005.class.php');
  $challenge2005 = new Challenge2005();
  $ins = $challenge2005->getInstances();
  foreach($ins as $instance)
    {
      echo $instance->getInstanceName() . '<br />';
      echo $instance->getAverageScore() . '<br />';
      $instance->computeAverage();
    }
  echo 'Done.';
}


function computeNormalizedMarkForAllSolutions()
{
  include_once('../model/classes/Challenge2005.class.php');
  $challenge2005 = new Challenge2005();
  $ins = $challenge2005->getInstances();
  foreach($ins as $instance)
    {
      $solutions = $instance->getSolutions();
      foreach($solutions as $solution)
	{
	  $solution->computeNormalizedMark($instance->getId());
	}
    }
}

function computeLadder()
{
  include_once('../model/classes/Challenge2005.class.php');
  $bdd = BDD::getBDD();
  $req = $bdd->query('select candidate_name, avg(normalized_mark) average from Solutions2005 s, Candidates2005 c where c.id=s.numCandidate group by numCandidate order by average DESC');
  while($result = $req->fetch())
    {
      echo $result['candidate_name'] . ' : ' .$result['average'] . '<br />';
    }
}

?>
