#!/usr/bin/python3

import os, sys
from lxml import html

SWF2JS_PATH="../js/swf2js.js"

class traite_fich_swf:
  def __init__(self, filepath):
    self.filepath=filepath
  
  def depthFromPepitRoot(self):
    f=''
    d=self.filepath
    depth=0
    while f!='exercices' and d!='':
      depth+=1
      d, f=os.path.split(d)
      
    if f=='':
      raise Exception("exercices folder not found!!")
    
    return(depth-1)
  
      
  def process(self):
    path, filenameOrig=os.path.split(self.filepath)
    filenameTarget=filenameOrig[:-4]+".html"
    targetPath=os.path.join(path, filenameTarget)
    print("will (re)create "+targetPath)
    
    playerPath=("../"*self.depthFromPepitRoot())+"js/swf2js-afkl.min.js"
    
    
    fp=open(targetPath, "w")
    fp.write('''<html>
  <head>
    <title>PEPIT des exercices &eacute;ducatifs de la maternelle au secondaire</title>
  </head>
  <style>
    body { margin: 0; }
  </style>
  <body>
    <a href="'''+filenameOrig+'''" style="display: none;" data-comment="for the file gets downloaded on web dump"></a>
    <script type="text/javascript" src="'''+playerPath+'''"></script>
    <script type="text/javascript">
        swf2js.load("'''+filenameOrig+'''");
    </script>
  </body>
</html>''')
    fp.close()






class traite_fich_html:
  def __init__(self, filepath):
    self.filepath=filepath
    self.boolModif=False
    #print("open "+filepath)
    with open(self.filepath, "r", errors='ignore') as f:
      self.xmlRoot=html.fromstring(f.read())
      f.close()
    
  def updateLinksToSwf(self):
    links=self.xmlRoot.xpath("//a")
    for linkNode in links:
      href=linkNode.attrib.get('href', '')
      if len(href)>4 and href.lower()[-4:]==".swf":
        nhref=href[:-4]+".html"
        linkNode.attrib['href']=nhref
        print(href+" ---> "+nhref)
        self.boolModif=True
      
  def process(self):
    self.updateLinksToSwf()
    
    if self.boolModif:
      self.save()
    
  def save(self):
    print("\nSaving modified file "+self.filepath+"...")
    fp=open(self.filepath, "wb")
    fp.write(html.tostring(self.xmlRoot, include_meta_content_type=True))
    fp.close()







for root, dirs, files in os.walk(".", topdown = False):
  for name in files:
    if len(name)>4 and (name.lower()[-4:]==".htm" or name.lower()[-5:]==".html"):
      tf=traite_fich_html(os.path.join(root, name))
      tf.process()
    if len(name)>3 and (name.lower()[-4:]==".swf"):
      tf=traite_fich_swf(os.path.join(root, name))
      tf.process()


