import re
from datetime import datetime
import os


def readResults(results, testname, graphBoolean):
    funcSplit = results.split("summary =")
    funcResultsLine = funcSplit[-1]
    funcReqMin = round(float(re.findall("(?<== )(.*)(?=\/s)", funcResultsLine)[0]) * 60, 2)
    funcAvgLatency = (re.findall("(?<=Avg:)(.*)(?= Min)", funcResultsLine)[0]).replace(" ", "")
    Time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')

    print("-----------------------------")
    print("Test:", testname)
    print("Requests/minute: ", funcReqMin)
    print("Average latency: ", funcAvgLatency)
    print("Time: ", Time)
    print("-----------------------------")

    if graphBoolean == "true":

        funcNewLine = Time + "," + funcAvgLatency + "," + str(funcReqMin)

        csvfile = "ResultCSV/"+testname+".csv"

        with open(csvfile, 'a+') as fd:
            fd.write(funcNewLine + "\n")

        funcGnuCommand = "gnuplot -e \"filepath='" + csvfile + "'; graafpath='" + "Graphs/GraphsLatency/"+testname + "'; graafititle='" + testname.replace("_", " ") + "'\" makeLatencyGraphs.sh"
        os.system(funcGnuCommand)
        funcGnuCommand = "gnuplot -e \"filepath='" + csvfile + "'; graafpath='" + "Graphs/GraphsRequestsMin/"+testname + "'; graafititle='" + testname.replace("_", " ") + "'\" makeRequestGraphs.sh"
        os.system(funcGnuCommand)

        with open("changes.csv", "a+") as f:
            f.write(checkChanges(csvfile, testname) + "," + funcAvgLatency + "\n")


def checkChanges(CSVfile, graphName):

    with open(CSVfile, 'r') as fd:
        content = fd.readlines()[-2:]
        firstResult = int(content[0].split(",")[1])

    try:
        secondResult = int(content[1].split(",")[1])

    except:
        secondResult = 0
        print("Running test " + graphName + " for the first time")

    if(secondResult == 0):
        changeOfPing = 0

    else:
        changeOfPing = secondResult-firstResult

    pingChangePercent = round((float(changeOfPing)/float(firstResult))*100, 1)
    newLine = graphName + "," + str(pingChangePercent)

    return newLine
