"""
Create graphs from results generated by simulations simulations
"""
import matplotlib.pyplot as plt


def normalize(data):
    """
    Normalize data into interval <0, 1>
    """
    total = sum(data)
    normalized = []
    for item in data:
        normalized.append(item/total)
    return normalized


def decypher(text):
    """
    Decypher file name into descriptive label for legend
    """

    # name shortcuts
    help_dict = {"h": "Target/Hunt AI", "p": "Probabilistic AI", "r": "Random AI"}
    final = ""
    t_split = text.split("-")
    final += help_dict[t_split[0]]

    # hunt/target AI branch
    if t_split[0] == "h":
        if t_split[1] == "True":
            final += ", parity"
        if t_split[2] == "True":
            final += ", cheating"
            final += "(knows "+t_split[3]+" ships)"

    # probabilistic AI branch
    if t_split[0] == "p":
        if t_split[1] == "True":
            final += ", cheating"
            final += "(knows "+t_split[2]+" ships)"
    return final


def create_graph(title, sources, output):
    """
    create distribution graph from sources, write to output image
    """
    data = []

    # open every data source file and add data to data list
    for source in sources:
        f = open(source, "r")
        temp = []
        for line in f:
            temp.append(int(line))
        f.close()
        data.append(temp)

    # create graph from data
    plt.figure(figsize=(20, 10), dpi=240)
    plt.title(title)
    for index, item in enumerate(data):
        plt.plot(normalize(item), label=decypher(sources[index][8:-4]))
    plt.legend()
    plt.xlabel("Game length(turns)")
    plt.savefig(output, bbox_inches="tight")
    plt.close()


def main():
    graph1 = ("results/h-False-False-0.txt", "results/h-True-False-0.txt",
              "results/p-False-0.txt", "results/r.txt")
    create_graph("AI game length distribution", graph1, "graphs/non_cheating.png")

    graph2 = ("results/h-True-True-2.txt", "results/h-True-True-5.txt",
              "results/p-False-0.txt", "results/h-True-False-0.txt",
              "results/p-True-2.txt", "results/p-True-5.txt")
    create_graph("Cheating AI game length distribution", graph2,
                 "graphs/cheating.png")

    graph3 = ["results/h-False-True-"+str(x)+".txt" for x in range(1, 6)]
    graph3.append("results/h-False-False-0.txt")
    create_graph("Hunt/Target(no parity) AI game length distribution",
                 graph3, "graphs/h-noparity.png")

    graph4 = ["results/h-True-True-"+str(x)+".txt" for x in range(1, 6)]
    graph4.append("results/h-True-False-0.txt")
    create_graph("Hunt/Target(parity) AI game length distribution",
                 graph4, "graphs/h-parity.png")

    graph4 = ("results/p-False-0.txt", "results/p-True-2.txt",
              "results/p-True-5.txt")
    create_graph("Probability AI game length distribution", graph4,
                 "graphs/probabilistic.png")

if __name__ == "__main__":
    main()
