#!/usr/bin/env python3

import numpy as np

from astropy import constants as cte
from astropy import units as u

import argparse

import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
import matplotlib as mpl

from pNbody.Mockimgs import luminosities

from astropy.io import fits

  
####################################################################
# option parser
####################################################################

description="plot Mass to Light ratio for a given metallicity and ages"
epilog     ="""
Examples:
--------
mockimgs_plotMLvsAgeFe 
mockimgs_plotMLvsAgeFe --filter BPASS230_JKC_U.hdf5
mockimgs_plotMLvsAgeFe --filter BPASS230_JKC_U
"""

parser = argparse.ArgumentParser(description=description,epilog=epilog,formatter_class=argparse.RawDescriptionHelpFormatter)




parser.add_argument("-o",
                    action="store",
                    type=str,
                    dest="outputfilename",
                    default=None,
                    help="Name of the output file")  

parser.add_argument("--filter",
                    action="store",
                    type=str,
                    default="BPASS230_SDSS_r",
                    help="Name of the filter or filter file")  

                    
####################################################################
# main
####################################################################



if __name__ == '__main__':
  
  opt = parser.parse_args()


  
  params = {
    "axes.labelsize": 14,
    "axes.titlesize": 18,
    "font.size": 12,
    "legend.fontsize": 12,
    "xtick.labelsize": 14,
    "ytick.labelsize": 14,
    "text.usetex": False,
    "figure.subplot.left": 0.1,
    "figure.subplot.right": 0.98,
    "figure.subplot.bottom": 0.11,
    "figure.subplot.top": 0.95,
    "figure.subplot.wspace": 0.02,
    "figure.subplot.hspace": 0.02,
    "figure.figsize" : (15*1.15, 15),    
    "lines.markersize": 6,
    "lines.linewidth": 3.0,
  }
  plt.rcParams.update(params)

  
  # define ages
  age_min =  0.01 # Gyr
  age_max = 14.0  # Gyr
  age_n   = 1000
  ages = 10**np.linspace(np.log10(age_min),np.log10(age_max),age_n)
  

  
  # define MH
  MHs    = np.array([-3,-2,-1,0])
  
  # define a filter
  lum = luminosities.LuminosityModel(opt.filter)
  
  # create the plot
  fig = plt.gcf()
  fig.set_size_inches(8,6)
  ax  = plt.gca()
    
  
  for MH in MHs:
    
    MH_s = np.ones(len(ages)) * MH
    
    # compute the SSP mass to light (through the filter) ratio
    MLs  = lum.MassToLightRatio(ages,MH_s,bolometric=False)
  
    
    ax.plot(ages,MLs,label="[M/H]=%d"%MH)
    
  
  #ax.semilogx()
  #ax.semilogy()
  
  # labels
  ax.set_xlabel(r"Age [Gyr]")
  ax.set_ylabel(r"M/L")  
  
  # legend
  ax.legend()
  
  ax.set_title(opt.filter)


  
  # save or display
  if opt.outputfilename:
    plt.savefig(opt.outputfilename)
  else:
    plt.show()
    






