#!/usr/bin/python3
##
from re import finditer
from base64 import b64decode,b64encode
from random import seed,randint,shuffle
import math


lines = open("compiled", "r").readlines()

decodees=[]
l=""
for lig in lines:
  l+=lig

l=l.strip()
if l[0]!='_' or l[-1]!='_':
  print("Abandon : absence de délimiteurs _.")
  
while l[0]=='_':
  l=l[1:]
while l[-1]=='_':
  l=l[:-1]
  
lignes=l.split()

def undojsescape(s):
  cha=""
  i=0
  while i<len(s):
    if s[i]!='%':
      cha+=s[i]
      i+=1
    else:
      if s[i+1]=='u':
        i+=6
      else:
        cha+=bytearray.fromhex(s[i+1:i+3]).decode('cp1252')
        i+=3
  return cha

for l in lignes:
  ldec=b64decode(l)
  lreps = ldec.decode('utf-8').split("&")[1:]
  decodees+=[undojsescape(r) for r in lreps]

g,nom,prenom,numetu=tuple(decodees[:4])
reponses=decodees[1:]
graine=int(g)+1105430

listeetu = ["nom","prenom","numetu"]
    
liste1 = ["vec1l0c1","vec1l0c2","vec1l1c1","vec1l1c2","vec1l2c1","vec1l2c2","vec1l3c1","vec1l3c2","vec1l4c1","vec1l4c2","vec1l5c1","vec1l5c2","vec1l6c1","vec1l6c2","vec1l7c1","vec1l7c2","vec1l8c1","vec1l8c2","vec1l9c1","vec1l9c2"]
liste2 = ["tab1l0c1","tab1l0c2","tab1l0c3","tab1l0c4","tab1l1c1","tab1l1c2","tab1l1c3","tab1l1c4","tab1l2c1","tab1l2c2","tab1l2c3","tab1l2c4","tab1l3c1","tab1l3c2","tab1l3c3","tab1l3c4","tab1l4c1","tab1l4c2","tab1l4c3","tab1l4c4","tab1l5c1","tab1l5c2","tab1l5c3","tab1l5c4","tab1l6c1","tab1l6c2","tab1l6c3","tab1l6c4","tab1l7c1","tab1l7c2","tab1l7c3","tab1l7c4","tab1l8c1","tab1l8c2","tab1l8c3","tab1l8c4","tab1l9c1","tab1l9c2","tab1l9c3","tab1l9c4"]

listerefs=listeetu+liste1+liste2

lignessujet = open("sujets/sujet_"+g.strip()+".html", "r").readlines()
  
sujet=""
for ligne in lignessujet:
  sujet+=ligne

def recherche(c,p,d1,d2):
  l1=len(d1)
  l2=len(d2)
  i=p
  b=True
  while i<len(c)-l1 and b:
    if c[i:i+l1]==d1:
      b=False
      i-=1
    i+=1
  j=i+l1
  b=True
  while j<len(c)-l2 and b:
    if c[j:j+l2]==d2:
      b=False
      j-=1
    j+=1
  return (c[i+l1:j],j+l2)
    
pos=0
while pos<len(sujet)-5:
  if sujet[pos:pos+5] not in ["input","INPUT"]:
      pos+=1
  else:
    if sujet[pos+6:pos+17]=='''type="text"''':
      (ch,pos)=recherche(sujet,pos+17,'id="','"')
      sujet=sujet[:pos]+' style="color: #a0a;" value="'+reponses[listerefs.index(ch)].strip()+'"'+sujet[pos:]
      pos+=7+len(reponses[listerefs.index(ch)])+1
    else:
      if sujet[pos+6:pos+16]=='type=radio':
        (name,pos)=recherche(sujet,pos+16,'name="','"')
        (value,pos)=recherche(sujet,pos,'value="','"')
        if reponses[listerefs.index(name)].strip()==value.strip():
          sujet=sujet[:pos]+' checked="checked"'+sujet[pos:]
          pos+=17
      else:
        pos+=1
        
file=open("sujets/copie_"+nom.strip().replace(' ','-',5)+"_"+prenom.strip().replace(' ','-',5)+"_"+numetu.strip()+".html",'w')
file.write(sujet)
file.close()

print("done\n")
