#!/usr/bin/env python3
# -*- coding: utf-8 -*-
""" Utils module with utility functions """

import pandas as pd


def format_floats(dataframe):
    """ Change all columns in a dataframe except for 'station',
        so that floats will be formatted to 2 digits after the decimal place

    Parameters
    ----------
    dataframe : pandas.core.frame.DataFrame
        Dataframe

    Returns
    -------
    pandas.core.frame.DataFrame
        Dataframe with formatted columns
    """

    for col in dataframe.columns:
        # check if the column is not 'station'
        if col != 'station':
            # convert the column to a string to allow for string formatting
            dataframe[col] = dataframe[col].astype(str)
            # iterate over the values in the column
            for i, val in enumerate(dataframe[col]):
                # check if the value is a float
                if '.' in val:
                    # if so, format it to have 2 decimal places
                    dataframe.at[i, col] = '{:.2f}'.format(float(val))

    return dataframe


def alphabetize_stations(dataframe):
    """ Alphabetize the stations for each region in the AERONET statistics table

    Parameters
    ----------
    dataframe : pandas.core.frame.DataFrame
        Dataframe

    Returns
    -------
    pandas.core.frame.DataFrame
        Dataframe with sorted columns
    """

    # Define a list of regions to sort between (in the desired order)
    regions = ['Europe', 'Mediterranean', 'MiddleEast', 'NAfrica', 'Total']
    region_dfs = []

    # Iterate over each pair of consecutive regions and sort the rows between them
    for i in range(len(regions)-1):
        # Get the indices of the current and next regions
        current_region_idx = dataframe[dataframe['station'] == regions[i]].index[0]
        next_region_idx = dataframe[dataframe['station'] == regions[i+1]].index[0]
        # Slice the dataframe to select the rows between the current and next regions
        subset_df = dataframe.loc[current_region_idx+1:next_region_idx-1]
        # Sort the rows alphabetically based on the 'station' column
        subset_df = subset_df.sort_values(by='station')
        # Create a new dataframe containing only the current region row
        current_region_row = dataframe.loc[current_region_idx].to_frame().T
        # Append the current region row and sorted subset dataframe to the list of region DataFrames
        region_dfs.append(current_region_row)
        region_dfs.append(subset_df)

    # Add the 'Total' row back to the end of the sorted dataframe
    total_row_idx = dataframe[dataframe['station'] == 'Total'].index[0]
    total_row = dataframe.loc[total_row_idx].to_frame().T
    region_dfs.append(total_row)

    # Concatenate all of the region DataFrames into a single sorted DataFrame
    sorted_df = pd.concat(region_dfs)

    return sorted_df
