#!/bin/python


def findPrefixFiles(prefix):
    Files = []
    for f in os.listdir("."):
        if f.startswith(prefix):
            Files.append(f)
    return Files


import os
ohjelmaPrefix = ["ml","mpl","mma"]
aiheMidfix = ["CF","D","Di","Li","F","G","K","V","A","P","T","Nl","M","Y","S","I"]
aihekansiot = ["CurveFit","Differentiaali","Diffint","Linis","Funktiot","Grafiikka","Kompleksi","Vektori","Aritmetiikka","Perusteet","Todari","Nonlinequ","Matriisi","Yhtalot","Sarja","Integraalimuunnos"]
shortToLong = dict(zip(aiheMidfix,aihekansiot))


os.chdir("./htXX")
for Pre in ohjelmaPrefix:
    if Pre == "ml":
        ohjelmaPostfix = "m"
    elif Pre == "mpl":
        ohjelmaPostfix = "mw"
    elif Pre == "mma":
        ohjelmaPostfix = "nb"
    for Mid in aiheMidfix:
        folder = Pre+"teht/"+Pre+shortToLong[Mid]+"/"
        exercises = findPrefixFiles(Pre+Mid)
        with open('../html/'+Pre+Mid+".html", 'w') as outfile:
            temp = open('../templateAlku.html')
            outfile.write(temp.read())
            temp.close()
            for fname in exercises:
                with open(fname) as infile:
                    for line in infile:
                        outfile.write(line)
                    outfile.write('<a href="../'+folder +fname.replace('htXX',"tex") +'" class=button>tex-koodi</a>')
                    if os.path.isfile( '../ratkaisut/'+fname.replace('.htXX',"R."+ohjelmaPostfix)):
                        outfile.write('<a href="../ratkaisut/'+fname.replace('.htXX',"R."+ohjelmaPostfix) +'" class=button>Ratkaisu</a>')
                    if os.path.isfile( '../ratkaisut/'+fname.replace('.htXX',"R.pdf")):
                        outfile.write('<a href="../ratkaisut/'+fname.replace('.htXX',"R.pdf") +'" class=button>Ratkaisu PDF-muodossa</a>')
                    if os.path.exist('../aputiedostot/'+fname.replace('.htXX','') ):
                        apufileet = os.listdir('../aputiedostot/'+fname.replace('.htXX',''))
                        for ff in apufileet:
                            outfile.write('<a href="../ratkaisut/'+ff +'" class=button>'+ff +'+</a>')
                        
                    outfile.write("<hl>")
                        
