import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

# In RSP, have rubin_sim phot_utils available, so add syseng_throughputs
# git clone git@github.com:lsst-pst/syseng_throughputs.git
# then pip install - 
# pip install . -e --no-deps

import syseng_throughputs as st
defaultDirs = st.setDefaultDirs()
hardware, system = st.buildHardwareAndSystem(defaultDirs)
eff_wavelen = {}
for b in 'ugrizy':
    eff_wavelen[b] = system[b].calc_eff_wavelen()[1]
wave_p = {}
wave_m = {}
for b in 'ugrizy':
    max_val = system[b].sb.max()
    wave_half = system[b].wavelen[np.where(system[b].sb > max_val / 2)]
    wave_p[b] = wave_half.max()
    wave_m[b] = wave_half.min()
d = pd.DataFrame([eff_wavelen, wave_p, wave_m], columns=['u', 'g', 'r', 'i', 'z', 'y'], index=['eff_wavelen', 'wave_p', 'wave_m']).T
d['fwhm'] = d['wave_p'] - d['wave_m']
d[['eff_wavelen', 'fwhm', 'wave_m', 'wave_p']]
plot_filter_colors_white_background = {'u': '#0c71ff', 'g': '#49be61', 'r': '#c61c00', 'i': '#ffc200', 'z': '#f341a2', 'y': '#5d0000'}
plot_filter_colors_black_background = {'u': '#3eb7ff', 'g': '#30c39f', 'r': '#ff7e00', 'i': '#2af5ff', 'z': '#a7f9c1', 'y': '#fdc900'}
plot_line_styles = {'u': '--', 'g': ':', 'r': '-', 'i': '-.', 'z': (0, (3, 5, 1, 5, 1, 5)), 'y': (0, (3, 1, 1, 1))}
colors = plot_filter_colors_white_background

plt.figure(figsize=(12, 6))
for b in 'ugrizy':
    plt.plot(system[b].wavelen, system[b].sb, color=colors[b], linestyle=plot_line_styles[b], 
             label=f"{b} @ {d.loc[b, 'eff_wavelen']:.0f} nm, FWHM {d.loc[b, 'fwhm']:.0f} nm")
    plt.axvline(d.loc[b, 'eff_wavelen'], ymin = 0.9, ymax=0.99, color=colors[b], alpha=0.7)
    plt.axvspan(d.loc[b, 'wave_p'], d.loc[b, 'wave_m'], ymin=.95, ymax=.96, color=colors[b], alpha=0.55)
plt.ylim(0.0, 0.7)
plt.xlim(300, 1100)
plt.grid(alpha=0.6)
plt.legend(loc=(0.865, 0.65), fancybox=True, framealpha=1)
plt.xlabel("Wavelength (nm)", fontsize='x-large')
plt.ylabel("Fractional throughput", fontsize='x-large')
plt.savefig("throughputs_bands.png", bbox_inches = 'tight')