import argparse
import matplotlib.pyplot as plt
from matplotlib import rc


def read_data(data_file):

    # Lists to store the data
    times = []
    values = []

    print(f"Reading: {data_file}")


    # Read data from the file
    with open(data_file, 'r') as file:
        for line in file:
            parts = line.strip().split()
            if len(parts) == 2:
                time_str, value_str = parts
                try:
                    # Convert time (mm:ss) to seconds
                    minutes, seconds = map(int, time_str.split(':'))
                    time_in_seconds = minutes * 60 + seconds
                    value = float(value_str)
                    times.append(time_in_seconds)
                    values.append(value)
                except ValueError:
                    print(f"Skipping invalid line: {line}")

    return (times, values)


def create_bar_plot(data_file_0, data_file_1, data_file_2, label_0, label_1, label_2,title, file_name):
    
    times_0, values_0 = read_data(data_file_0)
    times_1, values_1 = read_data(data_file_1)
    times_2, values_2 = read_data(data_file_2)

    rc('font', **{'family': 'serif', 'serif': ['Computer Modern'],'size': 24})
    rc('text', usetex=True)

    plt.figure(figsize=(10, 8))
    
    plt.plot(times_0, values_0,'r--', label=label_0, linewidth=3.0) 
    plt.plot(times_1, values_1,'b-', label=label_1, linewidth=3)  
    plt.plot(times_2, values_2,'k*-', label=label_2, linewidth=3.0)  

    # Label the axes and add a title
    plt.xlabel('Time (s)',fontsize=24)
    plt.ylabel('Average number of people',fontsize=24)
    plt.title(title,fontsize=24)

    plt.legend(fontsize=24)
    plt.grid()

    plt.savefig(file_name, format='pdf', bbox_inches='tight')

    # Show the plot
    plt.show()

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='Create people counting plot.')
    parser.add_argument('data_file_0', type=str, help='Path to the data file')
    parser.add_argument('data_file_1', type=str, help='Path to the data file')
    parser.add_argument('data_file_2', type=str, help='Path to the data file')
    parser.add_argument('label_0', type=str, help='Label data 0')
    parser.add_argument('label_1', type=str, help='Label data 1')
    parser.add_argument('label_2', type=str, help='Label data 2')
    parser.add_argument('file', type=str, help='File name')
    args = parser.parse_args()

    data_file_0 = args.data_file_0
    data_file_1 = args.data_file_1
    data_file_2 = args.data_file_2
    label_0 = args.label_0
    label_1 = args.label_1
    label_2 = args.label_2
    file_name = args.file

    print(f"Args: {data_file_0, data_file_1, data_file_2, label_0, label_1, label_2, file_name}")
    create_bar_plot(data_file_0, data_file_1, data_file_2, label_0, label_1, label_2, 'Average occupancy (30s moving average)', file_name)