# ==============================================================================
"""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"""
  matrix = read_csv(name) # read whole content of file 'name'
  rows, cols = len(matrix), len(matrix[0]) # get matrix size from data file
  new_name = name.split('.')[0] # get the file name without extension
  new_name = new_name+'.html' # add the html extension to the name
  # ----------------------------------------------------------------------------
  # begining of the html file
  html_begin=f"""
<!DOCTYPE html>
<html lang="fr">
 
  <head>
    <meta charset="utf-8" />
    <title>
      {name}
    </title>
  </head>
	
  <body>
    <h1>Fichier {name}</h1>
    <table border="1">
"""
  # ----------------------------------------------------------------------------
  # ending of the html file
  html_end = """
    </table>
  </body>
</html>
"""
  # ----------------------------------------------------------------------------
  # add to each cell the <td> </td> mark up
  table = [[f"<td>{cell}</td>" for cell in row] for row in matrix]
  # convert each row from list to string and add the <tr> </tr> mark up
  table = [ "<tr>\n"+'\n'.join(row)+"</tr>\n" for row in table]
  # convert the table list into string
  table = '\n'.join(table)
  # add the begining and the eand of the html file for finishing the treatment
  result = html_begin + table + html_end
  # save the resultat into the new html file
  write_txt(new_name, result)
# ------------------------------------------------------------------------------
def parser(command:str) -> str:
  """parse 'command' and return content of provided files with line numbering"""
  names = parse(command); #inspect()
  if type(names) is str:
    csv_html(names)
  else:
    for name in names:
      csv_html(name)
  return f"{command} converted"
# ==============================================================================
if __name__ == '__main__':
  userloop(parser, "Enter <filename> [filename ...]")
# ==============================================================================
