import os
import numpy as np
import matplotlib.pyplot as plt

FONT_SIZE = 16
LEGEND_SIZE = 14
LINE_WIDTH = 4


def produce_and_save_and_or_output_plot(path_to_evaluation_data, no_output, shall_overwrite, where_to_save=None):
    set_up_plot()
    add_to_plot(path_to_evaluation_data)
    finish(no_output, shall_overwrite, where_to_save)


def set_up_plot():
    plt.rc('font', size=FONT_SIZE)  # controls default text sizes
    plt.rc('axes', titlesize=FONT_SIZE)  # fontsize of the axes title
    plt.rc('axes', labelsize=FONT_SIZE)  # fontsize of the x and y labels
    plt.rc('legend', fontsize=LEGEND_SIZE)  # legend fontsize
    plt.plot([], [], 'black', linestyle='-', label="Combined Size of All Projections", linewidth=LINE_WIDTH)


def add_to_plot(folder_path):
    filename = folder_path + "state_explosion/evaluation_data_state_explosion.txt"
    data = np.loadtxt(filename, skiprows=1)
    size_global_type = data[:, 0]
    size_projs = data[:, -1]
    plt.xlim([0, 1.05*max(size_global_type)])
    plt.yscale("log")
    plt.ylim([1, 1.5*max(size_projs)])
    plt.xlabel("Size of Global Type")
    plt.legend(loc='best')
    plt.plot(size_global_type, size_projs, linestyle='-', color='black', linewidth=LINE_WIDTH)


def finish(no_output, shall_overwrite, where_to_save):
    if where_to_save is not None:
        file_exists = os.path.exists(where_to_save)
        if shall_overwrite or not file_exists:
            plt.savefig(where_to_save, format='pdf', bbox_inches='tight')
    if not no_output:
        plt.show()
    plt.clf()