"""
Functions to help filter the data based on the parameters gathered on
inspection.
"""
import numpy as np
import matplotlib.pyplot as plt


def min_max_filtering(parameters,  norm=0.3):
    """
    Filter on the left of the minimum distribution, and to right on the maximum distribution
    on the parameters file.
    
    Parameters
    ----------
        parameters: pd.DataFrame
            dataframe with parameters generated by the inspect function.
            
        norm: float
            number to scale bin width based on standard deviation.
    
    Returns
    -------
        filtered: pd.Series
            Images files after filtering.
    """
    
    # Show distributions
    _, axes = plt.subplots(1, 3, sharey=True, figsize=(15,5))
    cols_to_look = ["min", "max", "FWHM"]
    bins = {}
    
    for ax, col in zip(axes, cols_to_look):
        bins[col] = np.arange(parameters[col].min(), parameters[col].max(), norm*parameters[col].std())
        parameters.hist(col, bins=bins[col], ax=ax)
        
        
    plt.show()
    
    # Starting interactive selection
    confirmed = False
    while not confirmed:
        # Ask for cuts
        min_cut = float(input("Set value to cut from to the right of the min distribution: "))
        max_cut = float(input("Set value to cut to from the left of the max distribution: "))
        
        # Make cuts
        mask = (parameters["max"] >= max_cut) & (parameters["min"] <= min_cut)
        filtered = parameters.loc[mask]
        
        # Print proportion of discarted rows
        print(f"This cut filters: {(~mask).sum()} Images ({(~mask).sum()/len(parameters)*100:.2f}% of the total data)")

        # Show cuts
        _, [before, after] = plt.subplots(2, 3, sharey="row", sharex="col", figsize=(15,10))
        cols_to_look = ["min", "max", "FWHM"] 

        for ax, col in zip(before, cols_to_look):
            parameters.hist(col, bins=bins[col], ax=ax)
                    
        for ax, col in zip(after, cols_to_look):
            filtered.hist(col, bins=bins[col], ax=ax)
        
        plt.show()
        # Ask for confirmation
        
        decision = input("Confirm selection? [y/n]")
        
        if decision == "y":
            confirmed = True
    
    return filtered
