import os
# -*- coding: utf-8 -*-

def generateLatencyGraphHTML(path):
    pictures = []

    for file in os.listdir(path):
        pictures.append(file)

    filler = ""
    for i in pictures:
        filler += "<center><img src='" + "../lastSuccessfulBuild/artifact/" + path + "/" + i + "'></center>" + "\n"

    message = """<html>
    <head></head>
    <body>
    """ + filler + """
    </body>
    </html>"""
    f = open('ResultHTML/graphs.html', 'w')
    f.write(message)
    f.close()

def generateRequestsMinGraphHTML(path):
    pictures = []

    for file in os.listdir(path):
        pictures.append(file)

    filler = ""
    for i in pictures:
        filler += "<center><img src='" + "../lastSuccessfulBuild/artifact/" + path + "/" + i + "'></center>" + "\n"

    message = """<html>
    <head></head>
    <body>
    """ + filler + """
    </body>
    </html>"""
    f = open('ResultHTML/graphsReq.html', 'w')
    f.write(message)
    f.close()


def generateChangesHTML(path):
    with open(path, "r") as f:
        data = f.readlines()

    content = ""

    results = {}

    for i in data:
        testName = i.split(",")[0]
        testChange = i.split(",")[1].strip("\n")
        testLatency = i.split(",")[2].strip("\n")


        results[testName] = [testLatency, testChange]


    for o in sorted(results, key=lambda i: -float(results[i][1])):
        flatping = results.get(o)[0]
        pingchange = results.get(o)[1]
        htmlname = o.replace("_", " ")
        if "-" not in str(results.get(o)):
            content += "<tr><td>" + htmlname.replace("Threads", "<br>Threads").replace("Duration", "<br>Duration") + '</td><td><font color="blue">'+ str(flatping) + '</font></td><td><font color="red">+' + str(pingchange) + "%</font>" + "</td></tr>"
        else:
            content += "<tr><td>" + htmlname.replace("Threads", "<br>Threads").replace("Duration", "<br>Duration") + '</td><td><font color="blue">'+ str(flatping) + '</font></td><td><font color="green">' + str(pingchange) + "%</font>" + "</td></tr>"


    message = """
    <!DOCTYPE html>
    <html>
    <script src="sorttable.js"></script>
    <head>
    <style>
    table, th, td {
      border: 1px solid black;
      border-collapse: collapse;
    }
    </style>
    </head>
    <body>
    
    <h2>Conclusion of results</h2>
    <p>Change in average latency compared to previous build</p>
    
    <table class="sortable" style="width:20%">
    <tr>
        <th><b>Test name</b></th>
        <th><b>Latency</b></th>
        <th><b>Change in latency</b></th>
    </tr>
    """+content+"""
    </table>
    
    </body>
    </html>
    """


    f = open('ResultHTML/changes.html', 'w')
    f.write(message)
    f.close()
