from copy import deepcopy
import os

import astropy.units as u
from astropy import constants
import fitsio
import numpy as np
import pandas as pd

from mock_catalog_SED.qsogen_4_catalog import qsosed
from igm_absorption import my_get_IGM_absorption

# Pre-load the posterior distribution for the AGN SED
from util import ROOT


FIL = {}
ROOT = os.getcwd()
def get_band_egg(band):

    if band in FIL:
        return FIL[band]

    band = band.replace("magabs_", "")
    with open(f"/usr/local/share/egg/filter-db/db.dat") as f:
        for line in f:
            name, filename = line.strip().split('=')
            if name == band:
                break
    FIL[band] = fitsio.read(f"/usr/local/share/egg/filter-db/{filename}")
    return FIL[band]


def get_flux_band(lam, flux, band):

    """
    Integrate the SED through the filter transmission curve

        lam in microns
        flux in uJy
    """

    # Get the filter
    fil = get_band_egg(band)
    lam_filter = fil["LAM"][0]
    res_filter = fil["RES"][0]

    # Estimate and renormalize the filter at the datapoints
    res_filter = np.interp(lam, lam_filter, res_filter, left=0, right=0)
    norm = np.trapz(res_filter, lam)

    # NOTE: no overlap between wavelengths and filter lambda?
    if norm == 0:
        return 0

    res_filter /= norm
    flux_band = np.trapz(flux * res_filter, x=lam)
    return flux_band


def write(filename, lam_in_um, flux_in_uJy):
    """Save the SED in EGG format"""
    if not os.path.exists(os.path.dirname(filename)):
        os.makedirs(os.path.dirname(filename))
    fitsio.write(filename, {"LAMBDA": np.array([lam_in_um]), "FLUX": np.array([flux_in_uJy])}, clobber=True)
