# ==============================================================================
"""CSV_HTML :  save a csv file content in a HTML file"""
# ==============================================================================
__author__  = "Philippe Blasi"
__version__ = "1.0"
__date__    = "2023-05-02"
__usage__   = """
User input : <filename> [filename ...]
App output : HTML file with the csv file content in a table"""
# ==============================================================================
from ezCLI import *
# ------------------------------------------------------------------------------
def csv_html(name:str) -> str:
  """save the name csv file content in a HTML file"""
  # ----------------------------------------------------------------------------
  # TODO : construct the new file name with html extension
  #        define the beginning and the end of the html file
  html_begin = """<!DOCTYPE html>
<html lang="fr">
    <head>
        <meta charset="utf-8">
        <title>
            Ressources pour les maths
        </title>
    </head>
    
    <body>
        <table border="1">\n"""
  
  html_end = """
         </table>
    </body>
</html>
"""
  
  #        read the file into a matrix (2D array)
  matrix = read_csv(name)

  name= name.split('.')[0]  # on enlève l'extension du fichier
  
  nb_row = len(matrix)
  nb_col = len(matrix)
  
  #        convert each cell into a cell off a html table <td>x</td>
  #        convert each row into a string and add the <tr> </tr> mark up
  # double boucle pour parcourir la matrice

  html_table= ""
  
  for row in range(nb_row):
    html_table += "            <tr>\n"
    for col in range(nb_col):
      # html_table += "<td>" + str(matrix[row][col]) + "</td>"
      html_table += f"               <td>{matrix[row][col]}</td>\n"
    html_table += "            </tr>\n"
      
  #        add the begining and the end of the html file to the result
  result = html_begin + html_table + html_end
  #        save the result into the new html file

  write_txt(f"{name}.html",result)
  # ----------------------------------------------------------------------------
  
# ------------------------------------------------------------------------------
def parser(command:str) -> str:
  """parse 'command' and return content of provided files with line numbering"""
  # TODO : call csv_html for each name file received in the command
  tuple_name = parse(command) ;# inspect()
  if type(tuple_name) is str:
    csv_html(tuple_name)
  else:
    for name in tuple_name:
      csv_html(name)

  return f"{command} converted"

# ==============================================================================
if __name__ == '__main__':
  userloop(parser, "Enter <filename> [filename ...]")
# ==============================================================================
