import os
import numpy as np
import h5py
from luts import Idx, read_mlut_hdf5

def convert(h5_filepath, ptcle, wvl, prop_list, output_path):

    """
    
    - wvl : 
        if None                       : all wavelengths written in ascii
        if list, numpy array or float : interpolation
    
    - prop_list: list of dictionnary of properties corresponding to 
                 the one stored in h5 file for the particle
                  [ { propertie1 : val1prop1, propertie2 : val1prop2 },
                    { propertie1 : val1prop1, propertie2 : val2prop2 },
                    { propertie1 : val2prop1, propertie2 : val1prop2 },
                  ]  

    """

    if wvl is not None:
        print('')
        print(' This should take  more dev to ensure that there is no ')
        print(' pb if interpolating while the file corresponds to instruments SRF intagrated values...')
        print('')
        return

    print("Reading "+h5_filepath)
    datasets = ["Cext",
                "single_scattering_albedo",
                "p11_phase_function",
                "p21_phase_function",
                "p34_phase_function",
                "p44_phase_function"]

    nphase_elem=4
    f=h5py.File(h5_filepath,"r")
    if "p22_phase_function" in list(f[ptcle]["data"].keys()):
        nphase_elem=6
        datasets.append("p22_phase_function")
        datasets.append("p33_phase_function")
    f.close

    mlut_opt = read_mlut_hdf5(h5_filepath, datasets, group=ptcle)
    mlut_opt.print_info()

    if wvl is not None:    
        if isinstance(wvl,float):
            wvl=np.array([wvl])
        mlut_opt = mlut_opt.sub({"wavelengths":Idx(wvl)}) 
        #mlut_opt.print_info()

    nteta = len(mlut_opt.axes["mu"])
    nwvl  = len(mlut_opt.axes["wavelengths"])
    
    for dict_prop in prop_list:
        dict_tmp = {}
        fout_path = output_path.split(".")[0]
        #print(dict_prop)
        for prop, val in dict_prop.items():
            dict_tmp[prop] = Idx(val)
            fout_path+="_"+prop+"-%05.2f"%val
        #print(dict_tmp)
        fout_path+="."+output_path.split(".")[1]
        msub_opt = mlut_opt.sub(dict_tmp) 

        print("Writing "+fout_path)
        f=open(fout_path,"w")
        f.write("# Optical properties to be used by ARTDECO \n")
        f.write("# \n")
        f.write("# Produced at HYGEOS \n")
        f.write("# \n")
        f.write("# Used model to obtain that properties is: \n")
        f.write(" undef \n")
        f.write("# Used material is: \n")
        f.write(" undef \n")
        f.write("# Number of phase matrix elements :\n")
        f.write(" %i  \n"%nphase_elem)
        f.write("# Number of wavelengths :\n")
        f.write(" %i  \n"%nwvl)
        f.write("#  lambda(microns)   nteta   Cext                   SSA            g \n")
        for iwvl in range(nwvl):
            s = "   %12.7e"%mlut_opt.axes["wavelengths"][iwvl]+"      %i"%nteta+"    %12.7e"%msub_opt["Cext"].sub({"wavelengths":iwvl}).data+"    %12.7e"%msub_opt["single_scattering_albedo"].sub({"wavelengths":iwvl}).data+"    -32768"
            f.write(s +" \n")
        f.write("# Phase matrix \n")
        for iwvl in range(nwvl):
            f.write("# lambda = %12.6f \n"%mlut_opt.axes["wavelengths"][iwvl])
            if nphase_elem==6:
                f.write("#         u              F11            F22             F33            F44               F21               F34 \n")
                for imu in range(nteta):
                    s = "   %12.7e"%mlut_opt.axes["mu"][imu]+ \
                        "   %13.7e"%msub_opt["p11_phase_function"].sub({"wavelengths":iwvl,"mu":imu}).data + \
                        "   %13.7e"%msub_opt["p22_phase_function"].sub({"wavelengths":iwvl,"mu":imu}).data + \
                        "   %13.7e"%msub_opt["p33_phase_function"].sub({"wavelengths":iwvl,"mu":imu}).data + \
                        "   %13.7e"%msub_opt["p44_phase_function"].sub({"wavelengths":iwvl,"mu":imu}).data + \
                        "   %13.7e"%msub_opt["p21_phase_function"].sub({"wavelengths":iwvl,"mu":imu}).data + \
                        "   %13.7e"%msub_opt["p34_phase_function"].sub({"wavelengths":iwvl,"mu":imu}).data
                    f.write(s +" \n")
            elif nphase_elem==4:
                f.write("#         u              F11            F44               F21               F34 \n")
                for imu in range(nteta):
                    s = "   %12.7e"%mlut_opt.axes["mu"][imu] + \
                        "   %13.7e"%msub_opt["p11_phase_function"].sub({"wavelengths":iwvl,"mu":imu}).data + \
                        "   %13.7e"%msub_opt["p44_phase_function"].sub({"wavelengths":iwvl,"mu":imu}).data + \
                        "   %13.7e"%msub_opt["p21_phase_function"].sub({"wavelengths":iwvl,"mu":imu}).data + \
                        "   %13.7e"%msub_opt["p34_phase_function"].sub({"wavelengths":iwvl,"mu":imu}).data
                    f.write(s +" \n")
        f.close()    

    return


if __name__=='__main__':

    prop_list = [{"humidity":00.},
                 {"humidity":50.},
                 {"humidity":70.},
                 {"humidity":80.},
                 {"humidity":90.},
                 {"humidity":95.},
                 {"humidity":98.},
                 {"humidity":99.},
                 ]
    aer_opac = [
        "opac_antarctic",
        "opac_arctic",
        "opac_cont_avg",
        "opac_cont_clean",
        "opac_cont_polluted",
        "opac_desert",
        "opac_maritime_clean",
        "opac_maritime_polluted",
        "opac_maritime_tropical",
        "opac_urban"
    ]             
    os.mkdir("/rfs/proj/artdeco_lib/opt/ascii/opac_fci")
    for aer in aer_opac:
        convert("/rfs/proj/artdeco_lib/opt/opt_opac_fci.h5", aer, None, prop_list, "/rfs/proj/artdeco_lib/opt/ascii/opac_fci/opt_"+aer+"_fci.dat")
    
    prop_list = []
    reffs = np.linspace(5.0,60.0, num=23)
    os.mkdir("/rfs/proj/artdeco_lib/opt/ascii/baum_ice_fci")
    for reff in reffs:
        prop_list.append({"reff":reff})
    convert("/rfs/proj/artdeco_lib/opt/opt_baum_ice_ghm_fci.h5", "ghm", None, prop_list, "/rfs/proj/artdeco_lib/opt/ascii/baum_ice_fci/opt_baum_ice_ghm_fci.dat")
    