from woufU import fraction_entiers,repertoires,ecrire2,sauv_ex,sauv_corr,nb2lettres,round2
from random import randint,shuffle,choice,random
from pylab import gca,figure,subplot,xlim,ylim,xticks,yticks,savefig,close
import pdfkit
from fractions import Fraction as f
config = pdfkit.configuration(wkhtmltopdf="C:\\Program Files\\wkhtmltopdf\\bin\\wkhtmltopdf.exe")
options = {
    'page-size': 'Letter',
    'margin-top': '0.75in',
    'margin-right': '0.75in',
    'margin-bottom': '0.75in',
    'margin-left': '0.75in',
    'encoding': "UTF-8",
    'quiet': ''
    }





def exercice1():
    htm="""<h2 style="font-size:120%; color:red;">Exercice 1 : Donne une écriture décimale des nombres :</h2><div style="margin-left:100px;font-size:16px"><ul>"""
    corr=htm
    liste1=[10,100,1000]
    liste2=[randint(23,98752) for i in range(3)]
    shuffle(liste1)
    for i in range(3):
        htm+="""<li>{}</li>""".format(fraction_entiers(liste2[i],liste1[i]))
    
        corr+="""<li>{0} = {1}</li>""".format(fraction_entiers(liste2[i],liste1[i]),ecrire2(liste2[i]/liste1[i]))
        
    ajout=[]     
    e=randint(3,39)
    ajout.append(str(e))
    sol=e
    n_milliemes=randint(1,9)
    ajout.append(fraction_entiers(n_milliemes,1000))
    sol+=n_milliemes/1000
    n2=randint(1,9)
    
    if choice(("p","f"))=="p":
        sol+=n2/10
        ajout.append(fraction_entiers(n2,10))
    else:
        sol+=n2/100
        ajout.append(fraction_entiers(n2,100))
        
    shuffle(ajout)
    htm+="""<li>{} + {} + {}</li>""".format(*ajout)
    corr+="""<li>{} + {} + {} = {}</li>""".format(*ajout,ecrire2(round2(sol,3)))   
    htm+="</ul></div>"

    corr+="</ul></div>"
    return htm,corr
def exercice2():
   
    htm="""<h2 style="font-size:120%; color:red;">Exercice 2 : Ecris les nombres suivants en lettres (de deux façons) :</h2><div style="margin-left:100px;font-size:16px"><ul>"""
    corr=htm
    liste=[]
    for i in range(8):
        liste.append(randint(1,123))

    for i in range(8):
        liste[i]=10* liste[i]+randint(2,9)
        
    for i in range(4): 
         htm+="""<li>{}</li>""".format(ecrire2(liste[2*i]+float("0."+str(liste[2*i+1]))))
         corr+="""<li>{}</li>""".format(ecrire2(liste[2*i]+float("0."+str(liste[2*i+1]))))
         corr+="""<ul><li>{} virgule {}</li>""".format(nb2lettres(liste[2*i])[:-1],nb2lettres(liste[2*i+1]).lower())
         texte=["centièmes.","millièmes.","dix-millièmes."]
         corr+="""<li>{} unités et  {} {}</li></ul>""".format(nb2lettres(liste[2*i])[:-1],nb2lettres(liste[2*i+1]).lower()[:-1],texte[len(str(liste[2*i+1]))-2])
    
    htm+="</ul></div>"
    corr+="</ul></div>"
    return htm,corr
def exercice3():
    noms=["dizaines de mille",
          "unités de mille",
          "centaines",
          "dizaines",
          "unités",
          "dixièmes",
          "centièmes",
          "millièmes",
          "dix-millièmes",
          "cent-millièmes"
          ]
    
    q=[0,1,2,3,4,5,6,7,8,9]
    shuffle(q)
    n=list("0123456789")
    while n[0]=="0" or n[-1]=="0":
        shuffle(n)
    n="".join(n)
    nb=int(n)/100000
    
    
    htm="""<h2 style="font-size:120%; color:red;">Exercice 3 : Dans le nombre {} :</h2><div style="margin-left:100px;font-size:16px"><ul>""".format(ecrire2(nb))
    corr=htm
    for i in range(4):
        htm+="""<li> Quel est le chiffre des {} ?</li>""".format(noms[q[i]])
        corr+="""<li> Le chiffre des {} est <span style="color:red;"> {} </span>.</li>""".format(noms[q[i]],n[q[i]])
    for i in range(2):
        htm+="""<li> Recopie et complète : {} est le chiffre des .............. .</li>""".format(n[q[i+4]])
        corr+="""<li> {} est le chiffre des <span style="color:red;"> {} </span>.</li>""".format(n[q[i+4]],noms[q[i+4]])
    for i in range(2):
        if noms[q[i+6]][0]=="u":
            accord="d'"
        else:
            accord="de "
        htm+="""<li> Quel est le nombre {}{} ?</li>""".format(accord,noms[q[i+6]])
        corr+="""<li> Le nombre {}{} est <span style="color:red;"> {} </span>.</li>""".format(accord,noms[q[i+6]],ecrire2(n[:q[i+6]+1]))
    
    htm+="</ul></div>"
    corr+="</ul></div>"
    

    return htm, corr

def exercice4():
    lettres=list("ABCDEFGH")
    shuffle(lettres)
    nb=list(range(1,29))
    nb.remove(10)
    nb.remove(20)
    shuffle(nb)
    htm="""<h2 style="font-size:120%; color:red;">Exercice 4 : </h2> <div style="margin-left:100px;font-size:16px">
    <p style="font-size:120%; color:red;">Sur une même doite graduée, place les points {},{} et {} 
    d'abscisses respectives :</p><ul><li> {} </li><li> {} </li><li> {} </li></ul>
     """.format(*lettres[:3],*[ecrire2(round2(n/10,1)) for n in nb[:3]])
    
    corr=htm     

    corr+="</div>"+aff_frac({lettres[0]:nb[0],lettres[1]:nb[1],lettres[2]:nb[2]})
    



    return htm+"</div>",corr

def exercice5():
   
    presque=randint(8,12)
    nombres=[round2(presque +0.5+ random(),4) for i in range(7) ]
    htm="""<h2 style="font-size:120%; color:red;">Exercice 5 : Range les nombres suivants par ordre croissant : </h2><div style="margin-left:100px;font-size:16px"><ul>"""
    for i in range(7):
        htm+="<li> {} </li>".format(ecrire2(nombres[i]))
    htm+="</ul>"
    
    corr=htm
    nombres.sort()
    corr+="""<p style="color:red; margin-left:-50px"> {} </p>""".format("&nbsp;&nbsp;&lt;&nbsp;&nbsp;".join([ecrire2(n) for n in nombres]))
    
    
    
    
    htm+="</ul></div>"
    corr+="</ul></div>"
    return htm, corr

def ppcm(*n):
    """Calcul du 'Plus Petit Commun Multiple' de n (>=2) valeurs entières (Euclide)"""
    if len(n)==1:
        return n[0]
    def _pgcd(a,b):
        while b: a, b = b, a%b
        return a
    p = abs(n[0]*n[1])//_pgcd(n[0], n[1])
    for x in n[2:]:
        p = abs(p*x)//_pgcd(p, x)
    return p

def get_key(val,my_dict):
    for key, value in my_dict.items():
         if val == value:
             return key
 
    return "There is no such Key"

def aff_frac(dico):

    
    #noms=list(dico.keys())
    listes=list(dico.values())
    #parts_unite=(ppcm(*[f.denominator for f in listes]))
    parts_unite=10
    rang_grad=0
    nb_frac=0
    abscisses=[]
    labels=[]
    while nb_frac<len(listes):
        abscisses.append(rang_grad)
        if rang_grad/parts_unite==int(rang_grad/parts_unite):
            labels.append(str(int(rang_grad/parts_unite)))
            if rang_grad in listes:
                nb_frac+=1
        elif rang_grad in listes:
            nb_frac+=1
            labels.append(get_key(rang_grad,dico))
        else:
            labels.append("")
        rang_grad+=1
    
    while (rang_grad-1)%parts_unite!=0:
         abscisses.append(rang_grad)
         if rang_grad/parts_unite==int(rang_grad/parts_unite):
            labels.append(str(int(rang_grad/parts_unite)))
         else:
            labels.append("")
         rang_grad+=1
            
    
    figure(figsize=(8,1), dpi=100)
    subplot(111)


    ax = gca()
    ax.spines['right'].set_color('none')
    ax.spines['top'].set_color('none')
    ax.spines['left'].set_color('none')
    ax.xaxis.set_ticks_position('bottom')
    ax.spines['bottom'].set_position(('data',0))


    xlim(0, len(abscisses))
    xticks(abscisses,labels)

    ylim(-1,1)
    yticks([0],
           [r''])

    savefig("temp.svg")
    
    with open ("temp.svg", "r") as g:
       a=g.read()
    close('all')
    del ax
    
    return a.replace("""<?xml version="1.0" encoding="utf-8" standalone="no"?>""","")

haut_de_page= """<h3 style="color:#a5a5c0; margin-bottom:-10px;">Fiche : {}</h3>"""
bas_de_page="""<div style="margin-top:-3px; text-align:right">
<p style="page-break-after: always"><a  href="https://site2wouf.fr">(C) https://site2wouf.fr (2021)</a></p></div>"""
fin="""<div style="margin-top:-3px; text-align:right">
<p><a  href="https://site2wouf.fr">(C) https://site2wouf.fr (2021)</a></p></div>"""
repertoires()
for j in range(1,401):
    print(j)
    enn1,corr1=exercice1()
    enn2,corr2=exercice2()
    enn3,corr3=exercice3()
    enn4,corr4=exercice4()
    enn5,corr5=exercice5()
    sauv_ex(j,enn1+enn2+enn3+enn4+enn5)
    sauv_corr(j,corr1+corr2+corr3+corr4+corr5)
    chaine=haut_de_page.format(str(j)+ "&nbsp;&nbsp;&nbsp;&nbsp;  1/3")
    chaine+="""<h1 style="color:red; text-align:center">&hearts;  Décimaux - Cycle 3</h1><div style="margin-left:100px;font-size:16px">"""+enn1+enn2+enn3+enn4+enn5+"</div>"
    chaine+=bas_de_page
    

    chaine+=haut_de_page.format(str(j)+ "&nbsp;&nbsp;&nbsp;&nbsp;  2/3")
    chaine+="""<h1 style="color:red; text-align:center">&hearts;  Décimaux - Cycle 3 - Correction -</h1><div style="margin-left:100px;font-size:16px">"""+corr1+corr2+corr3+corr4+"</div>"
    chaine+=bas_de_page
    
   
    chaine+=haut_de_page.format(str(j)+ "&nbsp;&nbsp;&nbsp;&nbsp;  3/3")
    chaine+="""<h1 style="color:red; text-align:center">&hearts;  Décimaux - Cycle 3 - Correction -</h1><div style="margin-left:100px;font-size:16px">"""+corr5+"</div>"


    chaine+=fin

    pdfkit.from_string(chaine,"exercices_pdf\exercices{0}.pdf".format(j),configuration=config,options=options)
