#*********************************************************************************************
#                                 Fait par JGP SOLDAT
#                               Maintenu par Kana-chan
#                             Pour l'Alliance Francophone
#                             Version 4.00, le 21 mai 2007  
#                           Première version 27 janvier 2001
#
#                     (Programme de création de la page score4.html)
#
#*********************************************************************************************

use Socket;
use DBI;
use Encode qw(decode encode);

$maintenu = "<a href=\"/code/fahCode.7z\" target=\"_blank\">Kana-chan</a> avec l'aimable participation de Dylav de Zebulon.fr";
$destWWW = "/var/www/html";
$homeWWW = "/"; "https://fah.chezmks.fr";

$test = 0;

sub place {
  local ($tot, $val, $record) = @_;
  return (($tot-$val+$record)-1);
}

sub format_number {
  local ($number) = @_;
  my $number_str = "".$number."";
  my $cpt_pl = length($number_str)-1;
  my $cpt_nb = 1;
  while ( $cpt_pl >= 0 ) {
    if ( $cpt_nb == 3 ) {
      if ( $cpt_pl > 0 and substr($number_str, $cpt_pl-1, 1) ne "-" ) {
        substr($number_str, $cpt_pl, 1) = "&#160;".substr($number_str, $cpt_pl, 1);
        $cpt_nb = 0;
      }
  }
  $cpt_nb++;
  $cpt_pl--;
  }
  return $number_str;
}

sub couleur {
  local ($myPos, $posEq, $diff, $retard) = @_;
  $myCouleur = "";
  if ($diff eq "???") {
    return " center";
  }
  if (($myPos > $posEq and $posEq >= 1) and (($diff < 0 and $retard == 0) or ($diff > 0 and $retard == 1))) {
    $myCouleur = " vert";
  } elsif (($myPos < $posEq and $posEq <= 100) and ($diff > 0)) {
    $myCouleur = " rouge";
  }
  return $myCouleur;
}

# Parametres de connection a la base de donnees
$bd    = '/tmp/memory/fah.db';
$identifiant = '';      # identifiant
$motdepasse  = '';

# Connection a la base de donnees mysql
print("Connexion a la base de donnees $bd\n");
$db = DBI->connect(
        "DBI:SQLite:dbname=$bd",
        $identifiant, $motdepasse, {RaiseError => 1}
      ) or die "Connection impossible a la base de donnees $bd !\n $! \n $@\n$DBI::errstr";

open(file, "pos1.res"); $b = <file>; close(file);
open(file, "pos.res"); $b1 = <file>; close(file);

$ip_fah = "https://foldingathome.org/";
$ip6 = "https://www.alliancefrancophone.org";
$version = "7.10";

open(file, '>:utf8', "$destWWW/score4.html");
@mois = ('janvier','f&eacute;vrier','mars','avril','mai','juin','juillet','ao&ucirc;t','septembre','octobre','novembre','d&eacute;cembre');
@jour = ('dimanche','lundi','mardi','mercredi','jeudi','vendredi','samedi');
($sec,$min,$heure,$jour,$mois,$annee,$jour2) = (localtime(time))[0,1,2,3,4,5,6];
if ($sec < 10) { $sec = "0".$sec; }
if ($min < 10) { $min = "0".$min; }
if ($heure < 10) { $heure = "0".$heure; }
if ($jour < 10) { $jour = "0".$jour; }
$annee += "1900";

($GMsec,$GMmin,$GMheure,$GMjour,$GMmois,$GMannee,$GMjour2) = (gmtime(time))[0,1,2,3,4,5,6];
if ($GMsec < 10) { $GMsec = "0".$GMsec; }
if ($GMmin < 10) { $GMmin = "0".$GMmin; }
if ($GMheure < 10) { $GMheure = "0".$GMheure; }
if ($GMjour < 10) { $GMjour = "0".$GMjour; }
$GMannee += "1900";

# $url_javascript = "http://fah-web.stanford.edu/cgi-bin/main.py?qtype=teampage&teamnum=";
$url_javascript = "https://stats.foldingathome.org/team/";
$url_seoc_team = "https://folding.extremeoverclocking.com/team_summary.php?t=";

@couleur_fond = ('#8CD4F6', '#C2B998', '#C1A0B9', '#C4C7C4', '#DAC7C3', '#A2BFE4', '#AADFAA');

#
# --- section <head> -----------------------------------------------------
#
print file ("<!DOCTYPE html>\n");
print file ("<html>\n");
print file ("<head>\n");
print file ("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF8\">\n");
print file ("<title>Diff&eacute;rence par semaine entre les &eacute;quipes chez Folding\@Home</title>\n");
print file ("<meta name=\"Author\" lang=\"fr, en-us\" content=\"JGP SOLDAT\">\n");
print file ("<meta name=\"Description\" content=\"Statistiques des performances de l'Alliance Francophone\">\n");
print file ("<meta name=\"Keywords\" LANG=\"fr\" content=\"JGP SOLDAT, calcul distribué, Folding\@home, Foldingathome, Stanford, Forum, Alliance Francophone, Québec, Quebec, France, français, francais, Folding at Home\">\n");
print file ("<meta name=\"Identifier-URL\" content=\"".$homeWWW."\">\n");
print file ("<meta name=\"Publisher\" content=\"JGP SOLDAT\">\n");
print file ("<link rel=\"stylesheet\" href=\"./site/StatStyle.css\" type=\"text/css\">\n");
print file ("<style>\n");
print file (".alliance  {background-color:#BDF !important;color:#800 !important}\n");
print file (".all-col2  {color:#800 !important}\n");
print file (".rouge     {color:#D00}\n");
print file (".vert      {color:#090}\n");
print file (".bleu      {color:#009}\n");
print file (".corps th  {background-color:".$couleur_fond[$jour2]."}\n");
print file (".center    {text-align:center}\n");
print file ("</style>\n");
print file ("</head>\n");
#
# --- section <body> -----------------------------------------------------
#
print file ("<body>\n");
print file ("<div id=\"container\">\n");
print file ("<div id=\"header\">\n");
print file ("<div id=\"logo\">\n");
print file ("<div class=\"wrapper\">\n");
print file ("<a href=\"".$ip6."\"><img style=\"width:1050px\" src=\"./site/images_site/logo_1050.png\" title=\"Statistiques de l'Alliance Francophone - Folding\"></a>\n");
print file ("</div>\n");
print file ("</div>\n");
print file ("</div>\n");
print file ("<div id=\"main\">\n");
print file ("<div id=\"navbar\">\n");
print file ("<ul class=\"nav\">\n");
print file ("<!--li><a href=\"https://www.alliancefrancophone.org/\">Accueil de l'Alliance</a></li-->\n");
print file ("<li><a href=\"../index.html\">Accueil des stats</a></li>\n");
print file ("<li><a href=\"../Alliance.html\">Classement membres de l'AF</a></li>\n");
print file ("<li><a href=\"../miniteam.html\">Classement mini-teams</a></li>\n");
print file ("<li><a href=\"./site/TeamsStats.html\">Statistiques</a></li>\n");
print file ("<li><a href=\"./site/TeamsPays.html\">Mini-teams pays</a></li>\n");
print file ("<li><a href=\"./site/TeamsActives.html\">Mini-teams actives</a></li>\n");
print file ("<li><a href=\"./site/TeamsSommeil.html\">Mini-teams en sommeil</a></li>\n");
print file ("<li><a href=\"https://forum.alliancefrancophone.org/\">Forum de l'Alliance</a></li>\n");
print file ("</ul>\n");
print file ("</div>\n");
print file ("<div id=\"content\">\n");
print file ("<a id=\"top\" name=\"top\"></a>\n");
print file ("<div class=\"parag\"><h4>Le classement diff&eacute;rentiel chez<br>&nbsp;</h4></div>\n");
print file ("<div class=\"parag\"><a href=\"".$ip_fah."\" target=\"_blank\"><img src=\"./images/folding5.gif\"></a></div>\n");
print file ("<p class=\"MAJ\">Mis &agrave; jour le ".$jour[$jour2]." ".$jour." ".$mois[$mois]." ".$annee." &agrave; $heure:$min, heure de Paris ($GMheure:$GMmin GMT)</p>\n");

$donner = "pos_general, numeroteam, score, wu, rec";
$pos = 0;
$membre = 0;
$vert = 0;
$ErrNum = 0;
if ($test == 1) { print("SELECT pos_general,numeroteam FROM equipe WHERE rec = ".$b."\n"); }
$do = $db->prepare("SELECT pos_general,numeroteam FROM equipe WHERE rec = ".$b);
$ErrNum = $do->execute() or die $DBI::errstr;
while ($ErrNum >= 0 and my @data = $do->fetchrow_array()) {
  $tri[$data[0]] = $data[1];
  $membre++;
  if ($data[1] eq "T51") {
    $pos = $data[0];
  }
}

$nb_semaines = 10;

$actuelle = ($nb_semaines+1)*7;
$b1 = $b-$actuelle;
if ($b1 < 0) {
  $b1 = 0;
}

$cpt = 0;
while ($cpt < $actuelle+1) {
  $ref[$cpt] = 0;
  $cpt++;
}

if ($test == 1) { print("SELECT rec,score FROM equipe WHERE numeroteam = 'T51' AND rec BETWEEN ".$b1." AND ".$b."\n"); }
$do = $db->prepare("SELECT rec,score FROM equipe WHERE numeroteam = 'T51' AND rec BETWEEN ".$b1." AND ".$b);
$ErrNum = $do->execute() or die $DBI::errstr;
$num2 = 1;
while ($ErrNum >= 0 and my @data = $do->fetchrow_array()) {
  $rec = place($actuelle+1, $b, $data[0]);
  $ref[$rec] = int($data[1]);
  $num2++;
}

$url = 0;
open(file_team, "url_team.team");
my @liste = <file_team>;
print("\nLISTE de URL = ".@liste."\n");
close(file_team);
foreach $line (@liste) {
  if ($line ne "\r\n") {
    $url++;
    ($nom_team[$url], $url_team[$url]) = split(/\|/,$line,2);
    $url_team[$url] =~ s/\n//g;
    $url_team[$url] =~ s/\r//g;
    if ($test == 1) {
      print $url.": ".$nom_team[$url];
      $tmp = 30-length ($url.": ".$nom_team[$url]);
      print(" " x $tmp);
      print $url_team[$url]."\n";
    }
  }
}

$num = 0;
$dif = 0;
$num1 = 0;
print("\nMembre: ".$membre."\n\n");
while ($num < $membre) {
  if ($num1 >= 200) { print file ("\n</table>"); $num1 = 0; }
#
# --- entêtes du tableau principal ---------------------------------------
#
  if ($num1 == 0) {
   print file ("<table class=\"corps\">\n");
   print file ("<tr>\n");
   print file ("<th rowspan=\"2\">Pos</th>\n");
   print file ("<th rowspan=\"2\">Noms d'&eacute;quipes</th>\n");
   print file ("<th rowspan=\"2\">Points</th>\n");
   print file ("<th rowspan=\"2\">Retard<br>(Semaine)</th>\n");
   print file ("<th colspan=\"15\">Diff&eacute;rence de production par semaine avec l'AF</th>\n");
   print file ("</tr>\n");
   print file ("<tr>\n");
   print file ("<th>Semaine</th><th>S-1</th><th>S-2</th><th>S-3</th><th>S-4</th><th>S-5</th><th>S-6</th><th>S-7</th>\n");
   print file ("<th>S-8</th><th>S-9</th><th>S-10</th>\n"); #<th>S-11</th><th>S-12</th><th>S-13</th><th>S-14</th>\n");
   print file ("</tr>\n");
  }
  $num++;
  
  $actuelle_u = $actuelle;
  $cpt = 0;
  while ($cpt < $actuelle_u+1) {
    $u[$cpt] = -1;
    $cpt++;
  }
  if ($test == 1) { print("SELECT numeroteam,rec,pos_general,score,wu FROM equipe WHERE numeroteam = '".$tri[$num]."' AND rec BETWEEN ".$b1." AND ".$b."\n"); }
  $do = $db->prepare("SELECT numeroteam,rec,pos_general,score,wu FROM equipe WHERE numeroteam = '".$tri[$num]."' AND rec BETWEEN ".$b1." AND ".$b);
  $ErrNum = $do->execute() or die $DBI::errstr;
  $compte = 0;
  while ($ErrNum >= 0 and my @data = $do->fetchrow_array()) {
    if ($test == 1) { print("Equipe [".$data[0]."]: "); }
    if ($tri[$num] eq $data[0]) {
      $compte++;
      $rec = place($actuelle_u+1, $b, $data[1]);
      if ($test == 1) { print("Record [".$rec."] => [".$data[1]."]\n") };
      $nom[$rec] = $data[0];
      $nom[$rec] =~ s/;/ /g;
      $posg[$rec] = $data[2];
      $u[$rec] = int($data[3]);
      $cpuday[$rec] = $data[4];
      $cpuhour[$rec] = 0;
    } 
  }
  
  if ($test == 1) { print("SELECT nomteam FROM liste_equipe WHERE numeroteam = '".$nom[$rec]."'\n"); }
  $do = $db->prepare("SELECT nomteam FROM liste_equipe WHERE numeroteam = '".$nom[$rec]."'");
  $ErrNum = $do->execute() or die $DBI::errstr;
  while ($ErrNum >= 0 and my @data = $do->fetchrow_array()) {
    $nom = $data[0];
  }
    
  if ($test == 1) {
    print($posg[$rec]." ".$nom." ");
    $tmp = 50-length($posg[$rec]." ".$nom." ");
    print(" " x $tmp);
    print("Points= ".$u[$rec]."\n");
  }

  @team = split(/T/, $nom[$rec]);
  $tt = $posg[$actuelle];
  $f_tt = format_number($tt);
#
# --- ligne d'une team ---------------------------------------------------
#     $is_alliance=1 pour l'Alliance Francophone. Particularités,
#     - couleurs de fond forcée (#FBB) et de police forcée (#000),
#     - nom écrit dans une couleur forcée (#800)
#     
  $is_alliance = 0;
  if ($nom eq "Alliance Francophone") {
    $is_alliance = 1;
  }
  if ($is_alliance == 0) {print file ("<tr>\n")}
  else                   {print file ("<tr class=\"alliance\" id=\"AF\">\n")}
# 
# --- colonne 1 (pos) ----------------------------------------------------
#
  print file ("<td align=\"right\"><a ");
  if ($is_alliance != 0) {print file ("class=\"alliance\" "); }
  print file ("href=\"".$url_javascript.$team[1]."\" target=\"_blank\">".$f_tt."</a></td>\n");

  if ($test == 1) { print("NOM [".$nom."]\n"); }   
  $tmp = 1;
  while ($tmp <= $url) { 
    if ($nom =~ /$nom_team[$tmp]/) {
      $allo1 = "<a ";
      if ($is_alliance != 0) { $allo1 .= "class=\"alliance\" "; }
      $allo1 .= "href=\"".$url_team[$tmp]."\" target=\"_blank\">".$nom_team[$tmp]."</a>";
      $nom =~ s/$nom_team[$tmp]/$allo1/g;
    }
    $tmp++;
  }
# 
# --- colonne 2 (nom) ----------------------------------------------------
#
  if ($is_alliance == 1) { print file ("<td class=\"all-col2\">$nom</td>\n"); }
  elsif ($compte < 7)    { print file ("<td class=\"bleu\">$nom</td>\n"); }
  else                   { print file ("<td>$nom</td>\n"); }

  $memoire = 0;
  $cpt_u = 0;
  while ($cpt_u < $actuelle_u+1) {
    if ($u[$cpt_u] == -1) { $u[$cpt_u] = $memoire; } else { $memoire = $u[$cpt_u]; }
    $cpt_u++;
  }

  @r = 0;
  @f_r = 0;
  $cpt = 0;
  while ($cpt < $nb_semaines+1) {
    $AA = ($u[$actuelle_u-$cpt*7]-$u[$actuelle_u-($cpt+1)*7])-($ref[$actuelle-$cpt*7]-$ref[$actuelle-($cpt+1)*7]);
    $BB = $ref[$actuelle-$cpt*7]-$ref[$actuelle-($cpt+1)*7];
    if ($compte > ($cpt+1) and $BB != 0) {
      $r[$cpt] = int($AA/$BB*100);
      $f_r[$cpt] = format_number($r[$cpt])."&nbsp;%";
      if ($r[$cpt] > 0) {
        $f_r[$cpt] = "+".$f_r[$cpt];
      }
    } else {
      $r[$cpt] = "???";
      $f_r[$cpt] = "???";
    }
    $cpt++;
  }
  
# 
# --- colonne 3 (points) -------------------------------------------------
#
  $f_u_actuelle_u = format_number($u[$actuelle_u]);
  print file ("<td class=\"right\"><a ");
  if ($is_alliance != 0) { print file ("class=\"alliance\" "); }
  print file ("href=\"".$url_seoc_team.$team[1]."\" target=\"_blank\">".$f_u_actuelle_u."</a></td>\n");
# 
# --- colonne 4 (retard) -------------------------------------------------
#
  $temp = 0;
  $u_retard = ($u[$actuelle_u]-$u[$actuelle_u-7])-($ref[$actuelle]-$ref[$actuelle-7]);
  if ($u_retard != 0) {
    $temp = int(($ref[$actuelle]-$u[$actuelle_u])/$u_retard);
    $f_temp = format_number($temp);
  }
  if ($is_alliance == 1) {
    print file ("<td class=\"center\">=</td>\n");
  } else {
    print file ("<td class=\"center".(couleur($pos, $tt, $temp, 1))."\">".$f_temp."</td>\n");
  }
#
# --- colonnes suivantes (semaines) --------------------------------------
#
  $cpt = 0;
  while ($cpt < $nb_semaines+1) {
    if ($is_alliance == 0) {
      print file ("<td class=\"right".(couleur($pos, $tt, $r[$cpt], 0))."\">".$f_r[$cpt]."</td>");
    } else {
      print file ("<td class=\"center\">=</td>");
    }
    $cpt++;
  }
  print file ("</tr>");
  $num1++;
}
print file ("</table>\n");

# 
# --- Bas de page --------------------------------------------------------
#
print file ("</div>\n</div>\n<div id =\"footer\">\n");
print file ("<div class=\"row_latest\">\n<div class=\"latest\">\n<div class=\"latest_text\">");
print file ("<p><a href=\"http://folding.fleucorp.net/installation.htm\" target=\"_blank\">Élaboré par JGP SOLDAT</a>&nbsp;-&nbsp;Maintenu par <a href=\"/code/fahCode.7z\" target=\"_blank\">Kana-chan</a> avec l'aimable participation de Dylav de Zebulon.fr&nbsp;-&nbsp;Version 7.10<a href=\"/\" class=\"top_button\">HOME</a><a href=\"#top\" class=\"top_button\">HAUT</a></p>\n");
print file ("</div>\n</div>\n</div>\n</div>\n</div>\n");

print file ("</body>\n");
print file ("</html>\n");

close(file);
print("\nFermeture du fichier score4.html");

$db->disconnect();

open(file, "$destWWW/score4.html");
@copy = <file>;
close(file);
open(file, ">vieux/score4-$b.html");
print file (@copy);
close(file);

print("\nFin du traitement\n");
exit;
1;
