import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import interp1d
from WEAVEify_routines.step_02_common_routines.wavelength_array_calculation import \
wavelength_array_calculation_main


def wavelength_resampling_routines_main(inp_dict):

    inp_dict               = wavelength_array_calculation_main(inp_dict)
    inp_dict_Flux          = inp_dict["inp_dict_Flux"]
    lambda_arr_obs         = inp_dict["lambda_arr_obs"]
    Flux_conv_arr          = inp_dict_Flux["Flux_conv_arr"]
    wavelength_total_arr   = inp_dict_Flux["wavelength_total_arr"]
    intrp_funct            = interp1d(wavelength_total_arr,Flux_conv_arr)
    Flux_resamp_arr        = intrp_funct(lambda_arr_obs)
    out_dict_flux_resamp   = {"Flux_resamp_arr":Flux_resamp_arr,\
                              "lambda_arr_obs":lambda_arr_obs}
    inp_dict_Flux.update(out_dict_flux_resamp)
    inp_dict.update({"inp_dict_Flux":inp_dict_Flux})
    return inp_dict

def compute_default_wavelength_arr(inp_dict):
    inp_path_param       = inp_dict["inp_path_param"]
    inp_file_lsf         = inp_dict["inp_file_lsf"]
    lambda_min_instr     = inp_dict["lambda_min_instr"]
    lambda_max_instr     = inp_dict["lambda_max_instr"]
    wavelength_total_arr = inp_dict["wavelength_total_arr"]
    lsf_data_arr         = np.loadtxt(inp_path_param + inp_file_lsf)
    N_pixel_per_R        = 3
    light_speed          = 3.e5
    N_pixel_total        = 0

    for lsf_indx in range(lsf_data_arr.shape[0]):
        lambda_min_lsf    = max(lsf_data_arr[lsf_indx,0],lambda_min_instr)
        lambda_max_lsf    = min(lsf_data_arr[lsf_indx,1],lambda_max_instr)
        dv_fwhm           = lsf_data_arr[lsf_indx,2]
        lambda_mid        = 0.5 *(lambda_min_lsf + lambda_max_lsf)
        R_val             = light_speed / dv_fwhm
        delta_lambda_reqd = lambda_mid / (R_val*N_pixel_per_R)
        N_pixel_region    = int((lambda_max_lsf - lambda_min_lsf) / delta_lambda_reqd)
        lambda_arr_region = np.linspace(lambda_min_lsf,lambda_max_lsf,N_pixel_region) 
        if lsf_indx == 0:
            lambda_arr_obs = lambda_arr_region.copy()
        else:
            lambda_arr_obs = np.concatenate([lambda_arr_obs,lambda_arr_region[1:]])

    inp_dict.update({"lambda_arr_obs":lambda_arr_obs})
    return inp_dict










