import psycopg2
import matplotlib.pyplot as plt
import re

def plot_two_graphs(x_values, y_values):
    y1_values = [y[0] for y in y_values]
    y2_values = [y[1] for y in y_values]
    
    plt.figure(figsize=(10, 5))
    plt.subplot(1, 2, 1)
    plt.plot(x_values, y1_values, marker='o', color='b', label='old sort')
    plt.xlabel('length')
    plt.ylabel('time')
    plt.title('time old sort')
    plt.legend()
    plt.grid(True)
    
    plt.subplot(1, 2, 2)
    plt.plot(x_values, y2_values, marker='s', color='g', label='new sort')
    plt.xlabel('length')
    plt.ylabel('time old sort')
    plt.title('time new sort')
    plt.legend()
    plt.grid(True)
    
    # Adjust layout to prevent overlap
    plt.tight_layout()
    
    # Display the plot
    plt.show()

def plot_on_single_graph(x_values, y_values):
    y1_values = [y[0] for y in y_values]
    y2_values = [y[1] for y in y_values]
    
    plt.figure(figsize=(10, 6))
    plt.plot(x_values, y1_values, marker='o', color='b', label='old sort')
    plt.plot(x_values, y2_values, marker='s', color='g', label='new sort')
    
    # Adding labels and title
    plt.xlabel('length')
    plt.ylabel('time')
    plt.title('bench')
    
    # Adding legend and grid
    plt.legend()
    plt.grid(True)
    
    plt.show()

def execute_query(x):
    try:
        connection = psycopg2.connect(
            dbname="postgres",
            user="username",
            host="localhost",
            port="5433"
        )
        cursor = connection.cursor()
        query = f"SELECT bench_int_sort({x});"
        cursor.execute(query)
        result = cursor.fetchone()[0]
        connection.close()
        return result
    except Exception as error:
        print(f"Error executing query: {error}")
        return None


def parse_result(result):
    time_regex = r'\d+\.\d+|\d+'
    
    time_matches = re.findall(time_regex, result)
    print(time_matches, result)
    
    if len(time_matches) < 3:
        raise Exception('cant parse')
    
    # Convert the matches to appropriate types
    old_sort_time = int(time_matches[0])
    new_sort_time = int(time_matches[1])
    percentage_difference = float(time_matches[2])
    
    return old_sort_time, new_sort_time, percentage_difference


def plot_percentage(x_values, y_values):
    plt.figure(figsize=(8, 6))
    plt.plot(x_values, y_values, marker='o', color='r')
    plt.xlabel('length')
    plt.ylabel('Percentage Difference')
    plt.grid(True)
    plt.show()

        

def main():
    #x_values = [10, 100, 1000, 10000, 100000] 
    x_values = list(range(1, 1000000, 10000))
    y_values = []

    for x in x_values:
        times = parse_result(execute_query(x))
        y_values.append(times)


    plot_two_graphs(x_values, y_values)
    plot_on_single_graph(x_values, y_values)
    plot_percentage(x_values, [y[2] for y in y_values])

    
    

if __name__ == "__main__":
    main()
