#!/usr/bin/env bash

# suppression des fichiers existants
echo "" > resultats_partiels_bruts.txt
rm resultats_partiels_bruts.txt
echo "" > resultats_partiels_out.txt
rm resultats_partiels_out.txt

# shuffle des bulletins
shuf resultats_complets_bruts.txt > resultats_complets_bruts_shuf.txt

NB_BULLETIN_TOTAL=$(wc --lines < resultats_complets_bruts_shuf.txt)
NUMERO_BULLETIN=0

# une line = un bulletin sous forme oral
cat resultats_complets_bruts_shuf.txt | while read line; do
  clear
  NUMERO_BULLETIN=$((NUMERO_BULLETIN + 1))
  # on ajoute la nouvelle ligne aux résultats bruts partiels
  echo $line >> resultats_partiels_bruts.txt
  # on génère le fichier resultats_partiels_out.txt, utilisé dans la suite de la boucle (les bulletins partiels "traduits")
  ./fill.py candidates.txt resultats_partiels_bruts.txt
  # affichage du bulletin en cours
  BALLOT=$(tail -1 resultats_partiels_out.txt)
  echo -e "Bulletin n°${NUMERO_BULLETIN} : ${BALLOT}\n"
  # utilisation de l'appli condorcet, on stocke le résultat dans le fichiet condorcet_output.txt
  ./vendor/bin/condorcet election --candidates candidates.txt --votes resultats_partiels_out.txt SchulzeWinning -p > condorcet_output.txt
  # On stocke la ligne du ou des gagnants dans ligne_gagnants_partiels.txt, à traiter dans toDot.py
  sed -e/Schulze/\{ -e:1 -en\;b1 -e\} -ed condorcet_output.txt > temp.txt && sed 4!d temp.txt > ligne_gagnants_partiels.txt
  # On extrait la matrice des duels vers matrice_duels.yaml, puis appelle toDot.py pour générer l'image du graphe dans graphe_partiel.dot.png
  sed '/For/,$!d' condorcet_output.txt > temp.txt && sed 1,2d temp.txt -i && sed '/+-/,$d' temp.txt -i && sed -r 's/\|//g' temp.txt > matrice_duels.yaml && ./toDot.py
  # création de l'image avec texte numéro bulletin dans graphe_partiel_avec_texte.png
  convert -fill black -pointsize 60 -draw "text 15,70 '${NUMERO_BULLETIN}/${NB_BULLETIN_TOTAL}'" graphe_partiel.dot.png graphe_partiel_avec_texte.png
  echo -e "Graphe mis à jour.\n"
  # on affiche le classement
  sed -e/Schulze/\{ -e:1 -en\;b1 -e\} -ed condorcet_output.txt
  sleep 2
done

#echo "Fin. ${NUMERO_BULLETIN} bulletins ont été comptabilisés."