#!/usr/bin/env python
# =========================================================================
#
#  Copyright NumFOCUS
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0.txt
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.
#
# =========================================================================
import sys, csv
import argparse
from pathlib import Path

"""Create a HTML table from a CSV file that has been generated by CompareITKandSITKFilters.py

By default it reads in filters.csv (the default file produced by CompareITKandSITKFilters.py)
and writes out filters.html.
"""


class bcolors:
    """A class to print colored text."""

    HEADER = "\033[95m"
    OKBLUE = "\033[94m"
    OKGREEN = "\033[92m"
    WARNING = "\033[93m"
    FAIL = "\033[91m"
    ENDC = "\033[0m"


def my_func(inname, outname, doxyFlag):



    fieldnames = ("Filter", "ITK", "SITK", "Remark", "ToDo")  # fields in the CSV file

    outfile = open(outname, "w")

    try:
        if doxyFlag:
            outfile.write("/** \\page Filter_Coverage Filter Coverage\n\n")

        table_start = """
<table>
<tr>
<th>Filter name</th>
<th>ITK</th>
<th>SimpleITK</th>
<th>Remarks</th>
<th>ToDo</th>
</tr>
"""
        outfile.write(table_start)

        with open(inname, "r") as fp:
            reader = csv.DictReader(fp)
            for row in reader:

                filt = row[fieldnames[0]]
                remark = ""
                todo = False

                iflag = sflag = False
                if len(row[fieldnames[1]]):
                    iflag = row[fieldnames[1]].lower() == "true"
                if len(row[fieldnames[2]]):
                    sflag = row[fieldnames[2]].lower() == "true"

                # Get the remark field from the file.
                if row[fieldnames[3]] is not None:
                    if len(row[fieldnames[3]]):
                        remark = row[fieldnames[3]]

                # Get the ToDo flag
                if len(row[fieldnames[4]]):
                    todo = row[fieldnames[4]].lower() == "true"

                if sflag:
                    if iflag:
                        color = "20FF20"  # Green
                    else:
                        color = "C0FFC0"  # Light Green
                else:
                    if todo:
                        color = "FFFFFF"  # White
                    else:
                        color = "FF7070"  # Red
                row_html = (
                    f"<tr bgcolor={color}>\n"
                    f"<td>{filt}</td>\n"
                    f"<td>{str(iflag)}</td>\n"
                    f"<td>{str(sflag)}</td>\n"
                    f"<td>{remark}</td>\n"
                    f"<td>{str(todo) if not sflag else ''}</td>\n"
                    "</tr>\n"
                )
                outfile.write(row_html)

    except Exception as e:
        print(f"Error: {e})")
        sys.exit(1)

    outfile.write("</table>\n")

    # Legend table
    legend_html = """
<p style="font-size:20px; margin-bottom:0px;"><b>Legend</b></p>
<table border=1>
<tr>
<th>Color</th>
<th>Meaning</th>
</tr>
<tr>
<td bgcolor=20FF20> </th>
<td>Supported by SimpleITK and ITK</td>
</tr>
<tr>
<td bgcolor=C0FFC0> </th>
<td>SimpleITK only filter</td>
</tr>
<tr>
<td bgcolor=FFFFFF> </th>
<td>ITK filter that we plan to support in the future</td>
</tr>
<tr>
<td bgcolor=FF7070> </th>
<td>ITK filter that we will not support</td>
</tr>
</table>
 """
    outfile.write(legend_html)

    if doxyFlag:
        outfile.write("*/\n")

    outfile.close()


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Create a HTML table from a CSV file that has been generated by CompareITKandSITKFilters.py")
    parser.add_argument("input_file", type=Path,  help="Input CSV file")
    parser.add_argument("output_file", type=Path,  help="Output HTML file")
    # add a --doxygen/--no-doxygen boolean flag
    parser.add_argument("--doxygen", default=False, action=argparse.BooleanOptionalAction, help="Generate a Doxygen file")

    args = parser.parse_args()

    # Create the output directory if it does not exist
    args.output_file.parent.mkdir(parents=True, exist_ok=True)

    # print the input and output file names
    print(f"Input file: {args.input_file}")
    print(f"Output file: {args.output_file}")

    my_func(args.input_file, args.output_file, args.doxygen)
