"""Controlling the config file"""

import os
import yaml
from datetime import datetime
import cftime
import time

def load_config(config_file):
    with open(config_file, 'r') as file:
        config = yaml.safe_load(file)
    return config

import matplotlib.pyplot as plt

class Plotter:
    def __init__(self, data_array, latitudes, longitudes):
        self.data_array = data_array
        self.latitudes = latitudes
        self.longitudes = longitudes

    def plot_with_markers(self, var,time_index, index_pairs, output_dir='plots'):
        """Plot data with markers at specified index pairs."""
        # Select the desired time slice
        data = self.data_array.isel(time=time_index)

        # Plot the data
        plot = data.plot()
        ax = plot.axes

        # Loop through each pair of indices and plot the markers
        print("self.data_array",self.data_array)
        print("index_pairs ", index_pairs)

        # Convert the list of strings to a list of tuples
        index_pairs_tuples = []

        for i in range(0, len(index_pairs), 2):
            i_index = int(index_pairs[i].strip('()'))
            j_index = int(index_pairs[i + 1].strip('()'))
            index_pairs_tuples.append((i_index, j_index))

        print("index_pairs_tuples",index_pairs_tuples)

        for i_index, j_index in index_pairs_tuples:
            print(i_index, j_index)
            value = self.data_array.isel(time=time_index, j=j_index, i=i_index).values
            lat = self.latitudes.isel(i=i_index, j=j_index).values
            lon = self.longitudes.isel(i=i_index, j=j_index).values

            # Add marker to the plot
            ax.plot(i_index, j_index, marker='x', color='red', markersize=10)
            ax.set_title(f'i:{i_index}, j:{j_index}, lat:{lat:.1f}, lon:{lon:.1f}, value:{value:.2e}')

            # Save the plot as an image
            output_path = f'{output_dir}/{var}_images_location_{i_index}_{j_index}.png'

            os.makedirs(output_dir, exist_ok=True)
            plt.savefig(output_path)

            # Optionally print details to console
            print(f'Index: ({i_index}, {j_index}), Value: {value:.2e}, Latitude: {lat:.1f}, Longitude: {lon:.1f}')

        # Show the final plot
        #plt.show()

    def plot_series(self, index_pairs):
        start_time_plot1 = time.time()
        print("start_time_plot1",start_time_plot1)
        # List of variables to plot (in lowercase)
        list_multivar = ['intpp']
        #    'intpp', 'no3', 'po4', 'si', 'thetao', 'mlotst',
        #    'dfe', 'zmesoos', 'zmicroos', 'rsntds'
        #]
        print("index_pairs",index_pairs)


        # Loop over each index pair
        for idx, (i_index, j_index) in enumerate(index_pairs):
            fig, axs = plt.subplots(
                len(list_multivar), 1, figsize=(15, 3 * len(list_multivar)),
                constrained_layout=True
            )

            for var_idx, var_name in enumerate(list_multivar):
                dataset = self.datasets.get(var_name)

                if dataset is not None:
                    # Check the level selection based on the variable name
                    if var_name in ['intpp', 'mlotst', 'zmesoos', 'zmicroos', 'rsntds']:
                        timeseries = dataset.isel(i=i_index, j=j_index)
                        lat = dataset.latitude.isel(i=i_index, j=j_index).values
                        lon = dataset.longitude.isel(i=i_index, j=j_index).values
                    else:
                        timeseries = dataset.isel(i=i_index, j=j_index, lev=6)
                        lat = dataset.latitude.isel(i=i_index, j=j_index).values
                        lon = dataset.longitude.isel(i=i_index, j=j_index).values

                    # Convert the 'time' coordinate to standard datetime
                    times = self.convert_cftime_to_datetime(timeseries['time'].values)

                    # Plot the timeseries directly
                    axs[var_idx].plot(times, timeseries.values)
                    axs[var_idx].set_title(
                        f'{var_name.upper()} for i={i_index}, j={j_index}, lat={lat:.0f}, lon={lon:.0f}'
                    )
                    axs[var_idx].set_xlabel('Time')
                    axs[var_idx].set_ylabel('Value')
                    axs[var_idx].grid(True)
                else:
                    axs[var_idx].text(
                        0.5, 0.5, f'{var_name} dataset not found',
                        horizontalalignment='center', verticalalignment='center'
                    )
                    axs[var_idx].set_title(
                        f'{var_name.upper()} for i={i_index}, j={j_index}'
                    )
                    axs[var_idx].set_xlabel('Time')
                    axs[var_idx].set_ylabel('Value')
                    axs[var_idx].grid(True)

            plt.suptitle(f'Timeseries for Location (i={i_index}, j={j_index})', fontsize=16)
            plt.savefig(f'{self.output_dir}/timeseries_location_{i_index}_{j_index}.png')
            plt.close(fig)

        print("All plots have been saved.")
        end_time_plot1 = time.time()
        time_used_plot1 = (end_time_plot1 - start_time_plot1)
        print("Time used for entire PLOT..../zzzz", f'{time_used_plot1:.4f}', "Seconds")
        print("Time used for entire PLOT..../zzzz", f'{time_used_plot1/60:.4f}', "Minutes")
        print("Time used for entire PLOT..../zzzz", f'{time_used_plot1/3600:.4f}', "Hours")
