"""

PCB_results.py - Script for generating HTML report


"""

import torch

class HTMLresults:

    def __init__(self, template_path, export_path, template):
        self.template = template
        self.template_path = template_path
        self.export_path = export_path
        self.template_file = open(self.template_path + template, "r")
        self.html = str(self.template_file.read())
        self.device = str(torch.cuda.get_device_name(0))
        if self.template == "results_template.html":
            self.segmentation_table_lines = ""
            self.save_segmentation_table()
        if self.template == "metrics_template.html":
            self.metrics_table = ""
            self.metrics_table_footer = ""
            self.graph_labels = ""
            self.graph_ap_25 = ""
            self.graph_ap_50 = ""
            self.graph_ap_75 = ""
            self.graph_f1 = ""
            self.graph_f2 = ""
        if self.template == "training_template.html":
            self.train_metrics_table = ""
            self.graph_labels = ""
            self.graph_ap_25 = ""
            self.graph_ap_50 = ""
            self.graph_ap_75 = ""
            self.graph_f1 = ""
            self.graph_f2 = ""

    def save_segmentation_table(self):
        flag_start = '$SEGMENTATION_TABLE_BEGIN$'
        flag_end   = '$SEGMENTATION_TABLE_END$'

        # Get line for the segmentation results
        self.segmentation_table_line = self.html[self.html.find(flag_start)+len(flag_start):self.html.rfind(flag_end)]
        self.html = self.html.replace(self.segmentation_table_line, '')\
            .replace(flag_start, '')\
            .replace(flag_end, '')

    def add_to_segmentation_table(self, path, name, segm_duration, instances, class_names, trigger_warning):
        time_h = segm_duration.split(":")[0]
        time_m = segm_duration.split(":")[1]
        time_m_s = segm_duration.split(":")[2]
        time_s = time_m_s[:2]
        time_ms = time_m_s[3:]
        line = self.segmentation_table_line
        line = line.replace("$IMAGE_PATH$", path)\
            .replace("$IMAGE_NAME$", name)\
            .replace("$SEGM_DURATION$", time_h + "h " + time_m + "m " + time_s + "s " + time_ms + "0ms ")

        line = line.replace("$INSTANCES_FOUND$", str(len(instances['scores'])))

        instances_table = ""
        for index, item in enumerate(instances['scores']):
            instances_table += "<tr><td>Class: "+str(class_names[instances['class_ids'][index]])+"</td><td>Score: "+str(round(instances['scores'][index],2))+"</td></tr>"

        line = line.replace("$INSTANCES$", instances_table)

        if trigger_warning:
          line = line.replace("$WARNING$", "<tr><td colspan='2'><div class='alert alert-danger' role='alert'>Hands detected, please remove hands!</div></td></tr>")
        else:
          line = line.replace("$WARNING$", "")

        self.segmentation_table_lines += line

    def get_val_class(self, value):
        if value > 0.6:
            return "table-success"
        elif value > 0.2:
            return "table-warning"
        return "table-danger"

    def add_to_metrics_table(self, path, AP_25, AP_50, AP_75, F1, F2):
        self.metrics_table += "<tr>" \
                              "<td>"+str(path)+"</td>" \
                              "<td class='"+self.get_val_class(AP_25)+"'>"+str(AP_25)+"</td>" \
                              "<td class='"+self.get_val_class(AP_50)+"'>"+str(AP_50)+"</td>" \
                              "<td class='"+self.get_val_class(AP_75)+"'>"+str(AP_75)+"</td>" \
                              "<td class='"+self.get_val_class(F1)+"'>"+str(F1)+"</td>" \
                              "<td class='"+self.get_val_class(F2)+"'>"+str(F2)+"</td>" \
                              "</tr>"
        self.graph_ap_25 += str(AP_25) + ','
        self.graph_ap_50 += str(AP_50) + ','
        self.graph_ap_75 += str(AP_75) + ','
        self.graph_f1 += str(F1) + ','
        self.graph_f2 += str(F2) + ','

    def add_to_metrics_table_footer(self, total, MAP_25, MAP_50, MAP_75, MF1, MF2):
        self.metrics_table_footer += "<td><strong>"+total+"</strong></td>" \
                                     "<td class='"+self.get_val_class(MAP_25)+"'><strong>"+str(MAP_25)+"</strong></td>" \
                                     "<td class='"+self.get_val_class(MAP_50)+"'><strong>"+str(MAP_50)+"</strong></td>" \
                                     "<td class='"+self.get_val_class(MAP_75)+"'><strong>"+str(MAP_75)+"</strong></td>" \
                                     "<td class='"+self.get_val_class(MF1)+"'><strong>"+str(MF1)+"</strong></td>" \
                                     "<td class='"+self.get_val_class(MF2)+"'><strong>"+str(MF2)+"</strong></td>"

    def create_train_metrics_table(self, log):
      e_num = 5
      for e in log:
        self.train_metrics_table += "<tr>"
        self.graph_ap_25 += str(e[1]) + ","
        self.graph_ap_50 += str(e[2]) + ","
        self.graph_ap_75 += str(e[3]) + ","
        self.graph_f1 += str(e[4]) + ","
        self.graph_f2 += str(e[5]) + ","
        self.add_to_labels(str(e_num))

        for x in range(0, 6):
          self.train_metrics_table += "<td>" + str(e[x]) + "</td>"

        self.train_metrics_table += "</tr>"
        e_num += 5


    def add_to_labels(self, label):
        self.graph_labels += '"' + label + '",'

    def replace(self, flag, content):
        self.html = self.html.replace(flag, content)

    def export(self):
      
      # Export images report
        if self.template == "results_template.html":
            self.html = self.html.replace("$SEGMENTATION_TABLE$", self.segmentation_table_lines)
            self.html = self.html.replace("$GPU$", self.device)

      # Export metrics report
        if self.template == "metrics_template.html":
            self.html = self.html.replace("$METRICS_TABLE$", self.metrics_table)
            self.html = self.html.replace("$METRICS_TABLE_FOOTER$", self.metrics_table_footer)
            self.html = self.html.replace("$GRAPH_AP_25_DATA$", self.graph_ap_25)
            self.html = self.html.replace("$GRAPH_AP_50_DATA$", self.graph_ap_50)
            self.html = self.html.replace("$GRAPH_AP_75_DATA$", self.graph_ap_75)
            self.html = self.html.replace("$GRAPH_F1_DATA$", self.graph_f1)
            self.html = self.html.replace("$GRAPH_F2_DATA$", self.graph_f2)
            self.html = self.html.replace("$GRAPH_LABELS$", self.graph_labels)
            self.html = self.html.replace("$GPU$", self.device)

      # Export training report
        if self.template == "training_template.html":
            self.html = self.html.replace("$TRAIN_METRICS_TABLE$", self.train_metrics_table)
            self.html = self.html.replace("$GRAPH_AP_25_DATA$", self.graph_ap_25)
            self.html = self.html.replace("$GRAPH_AP_50_DATA$", self.graph_ap_50)
            self.html = self.html.replace("$GRAPH_AP_75_DATA$", self.graph_ap_75)
            self.html = self.html.replace("$GRAPH_F1_DATA$", self.graph_f1)
            self.html = self.html.replace("$GRAPH_F2_DATA$", self.graph_f2)
            self.html = self.html.replace("$GRAPH_LABELS$", self.graph_labels)
            self.html = self.html.replace("$GPU$", self.device)

        export = open(self.export_path + '/results.html', 'w')
        export.write(self.html)
        export.close()

    def print(self):
        print(self.html)
