import galsim
import pylab as pl
import numpy as np

class FilterParam(object):
    def __init__(self, filter_dir=None, filter_param=None):
        self.param = self._filtParam(filter_param)
        if filter_dir is not None:
            self.filter_dir = filter_dir
        else:
            self.filter_dir = None

    def _filtParam(self, filter_param=None):
        """
        TODO: subject to change
        Basic parameters of the CSSOS filters.
        """
        # filter parameters: name: 
        # 1) effective wavelength
        # 2) effective width
        # 3) blue end
        # 4) red end
        # 5) systematic efficiency:
        #    tau = quantum efficiency * optical transmission * filter transmission
        # 6) sky background: e/pix/s
        # 7) saturation magnitude
        # 8) dim end magnitude
        if filter_param == None:
            filtP = {
                    "nuv":   [2867.7,   705.4,  2470.0,   3270.0,  0.1404, 0.004, 15.7, 25.4],
                    "u":     [3601.1,   852.1,  3120.0,   4090.0,  0.2176, 0.021, 16.1, 25.4],
                    "g":     [4754.5,  1569.8,  3900.0,   5620.0,  0.4640, 0.164, 17.2, 26.3],
                    "r":     [6199.8,  1481.2,  5370.0,   7030.0,  0.5040, 0.207, 17.0, 26.0],
                    "i":     [7653.2,  1588.1,  6760.0,   8550.0,  0.4960, 0.212, 16.7, 25.9],
                    "z":     [9600.6,  2490.5,  8240.0,  11000.0,  0.2000, 0.123, 15.7, 25.2],
                    "y":     [10051.0, 1590.6,  9130.0,  11000.0,  0.0960, 0.037, 14.4, 24.4],
                    
                    "GU":    [0.0,        0.0,  2550.0,   4200.0,     1.0, 0.037, 14.0, 26.0],
                    "GV":    [0.0,        0.0,  4000.0,   6500.0,     1.0, 0.037, 14.0, 26.0],
                    "GI":    [0.0,        0.0,  6200.0,  10000.0,     1.0, 0.037, 14.0, 26.0],
                    }
        else:
            filtP = filter_param

        return filtP

    def filtsInterp(self, filtlistn, filtdir="./", unit="A"):
        """
        read filters and save into Python dictionary
        NOTE: the wavelength unit must be in "Angstrom"
        
        Parameters:
        Same as function 'seds'
        
        Return:
        Same as function 'seds'
        """
        filtParams = self.param
        filtype = list(filtParams.keys())

        filts = {}
        filtlist = filtdir + filtlistn
        filtn = open(filtlist).read().splitlines()
        for itype in filtype:
            ifiltn = filtdir+itype+".dat"
            iblim = filtParams[itype][2]
            irlim = filtParams[itype][3]
            ifilt =  galsim.Bandpass(ifiltn,wave_type=unit,blue_limit=iblim,red_limit=irlim)
            wave  = ifilt.wave_list
            ifilt = ifilt.func(wave)
            filts[itype] = np.transpose(np.array([wave*10.0,ifilt]))

        return filtype, filts