import galsim
import os
from astropy.time import Time as asTime

def ConfigDir(cat_dir=None, work_dir=None, data_dir=None, config_file_path=None):
    path_dict = {}
    # Working directory
    if work_dir == None:
        dirname, _ = os.path.split(os.path.abspath(__file__))
        path_dict["work_dir"] = "/".join(dirname.split("/")[:-1]) + "/"
    else:
        path_dict["work_dir"] = work_dir
    
    # Configuration file
    if config_file_path is not None:
        path_dict["config_file"] = config_file_path
    else:
        path_dict["config_file"] = os.path.join(path_dict["work_dir"], "ObservationSim.cfg")
    
    # Output directories
    # path_dict["output_fig_dir"] = os.path.join(path_dict["work_dir"], "figure/")
    # if not os.path.exists(path_dict["output_fig_dir"]):
    #     os.system("mkdir %s"%path_dict["output_fig_dir"])
    # path_dict["output_cat_dir"] = os.path.join(path_dict["work_dir"], "scat/")
    # if not os.path.exists(path_dict["output_cat_dir"]):
    #     os.system("mkdir %s"%path_dict["output_cat_dir"])
    # path_dict["output_img_dir"] = os.path.join(path_dict["work_dir"], "simg/")
    # if not os.path.exists(path_dict["output_img_dir"]):
    #     os.system("mkdir %s"%path_dict["output_img_dir"])
    
    # Data directory
    if data_dir == None:
        path_dict["data_dir"] =os.path.join(path_dict["work_dir"], "data/")
    else:
        path_dict["data_dir"] = data_dir
    # Data sub-catalogs
    # Object catalog direcotry
    # path_dict["cat_dir"] = os.path.join(path_dict["data_dir"], "catalog_points_7degree2/", cat_dir)
    path_dict["cat_dir"] = os.path.join(path_dict["data_dir"], "Catalog_20210126")
    # PSF data directory
    path_dict["psf_dir"] = os.path.join(path_dict["data_dir"], "csstPSFdata/CSSOS_psf_20210108/CSST_psf_ciomp_2p5um_cycle3_ccr90_proc")
    # SED catalog directory
    path_dict["SED_dir"] = os.path.join(path_dict["data_dir"], "imageSims/Catalog/SEDObject")
    path_dict["template_dir"] = path_dict["data_dir"] + "Templates/"
    # Directories/files for instrument parameters, e.g. efficiency curves.
    path_dict["filter_dir"] = os.path.join(path_dict["data_dir"], "Filters")
    path_dict["ccd_dir"] = os.path.join(path_dict["data_dir"], "Filter_CCD_Mirror/ccd")
    path_dict["mirror_file"] = os.path.join(path_dict["data_dir"], "Filter_CCD_Mirror/mirror_ccdnote.txt")

    # Cosmic-ray data directory:
    path_dict["CRdata_dir"] = os.path.join(path_dict["data_dir"], "CRdata")

    # Slitless spectroscopy realted
    path_dict["sls_dir"] = os.path.join(path_dict["data_dir"], "CONF/")
    path_dict["normalize_dir"] = os.path.join(path_dict["data_dir"], "normalize_filter/")

    return path_dict

def ReadConfig(config_filename):
    """Read in a configuration file and return the corresponding dict(s).

    Parameters:
        config_filename:    The name of the configuration file to read.
    Returns:
        (list) of config dicts
    """
    config = {}
    config_file = open(config_filename).readlines()
    nlines = len(config_file)
    for i in range(nlines):
        row = config_file[i].split()
        if len(row) <= 1: continue # blank row
        if not "#" in row:
            if len(row) == 2:
                key, val = row[0:2]
                config.update({key:val})
            else:
                print("!! Something is wrong with parameter '%s'."%row[0])
                return
        elif row.index("#") == 2:
            key, val = row[0:2]
            config.update({key:val})
        elif row.index("#") == 0:
            continue # annotation
        else:
            print("!! Something is wrong with parameter '%s'."%row[0])
            return
    config = ParseConfig(config)
    return config

def ParseConfig(config):
    """Parse the config values to the right type

    Parameters:
        config:     raw config dict 
    Returns:
        Parsed config dict
    """
    config["ra_center"]     = float(config["ra_center"])
    config["dec_center"]    = float(config["dec_center"])
    config["psf_rcont"]     = config["psf_rcont"].split(",")
    config["psfRa"]         = float(config["psf_rcont"][0])
    config["psfCont"]       = float(config["psf_rcont"][1])
    config["image_rot"]     = float(config["image_rot"])*galsim.degrees
    config["sigma_spin"]    = float(config["sigma_spin"])
    config["reduced_g1"]    = float(config["reduced_g1"])
    config["reduced_g2"]    = float(config["reduced_g2"])
    config["rotateEll"]     = float(config["rotateEll"])
    config["reEll"]         = int(config["rotateEll"]/45.0)
    if config["reEll"]==0: config["reIndex"] = "P"
    if config["reEll"]==1: config["reIndex"] = "X"
    if config["reEll"]==2: config["reIndex"] = "N"
    if config["reEll"]==3: config["reIndex"] = "Y"
    config["seed_flat"]     = int(config["seed_flat"])
    config["seed_prnu"]     = int(config["seed_prnu"])
    config["seed_star"]     = int(config["seed_star"])
    config["seed_gal"]      = int(config["seed_gal"])
    config["seed_Av"]       = int(config["seed_Av"])
    config["bias_level"]    = int(config["bias_level"])
    config["df_strength"]   = float(config["df_strength"])
    return config