from ObservationSim.ObservationSim import Observation
from ObservationSim._util import parse_args, generate_pointings, make_run_dirs
from Catalog.Catalog_example import Catalog_example
import os
import galsim
import yaml

import gc
gc.enable()

def runSim(Catalog):
    """
    Main method for simulation call.
    """
    args = parse_args()
    if args.config_dir is None:
        args.config_dir = ''
    args.config_dir = os.path.abspath(args.config_dir)
    args.config_file = os.path.join(args.config_dir, args.config_file)
    with open(args.config_file, "r") as stream:
        try:
            config = yaml.safe_load(stream)
            for key, value in config.items():
                print (key + " : " + str(value))
        except yaml.YAMLError as exc:
            print(exc)
    config["obs_setting"]["image_rot"] = float(config["obs_setting"]["image_rot"])*galsim.degrees

    # Overwrite the data and working directories
    # if they are specified by the command line inputs
    if args.data_dir is not None:
        config['data_dir'] = args.data_dir
    if args.work_dir is not None:
        config['work_dir'] = args.work_dir

    # Generate lists of RA, DEC, time_stamps, pointing_type (MS or CAL), and pRange 
    # (selections of pointings to run) based on the input pointing list (or default 
    # pointing RA, DEC) and "config["obs_setting"]["run_pointings"]".
    # "config['obs_setting']['np_cal']"" is the number of CAL pointings which will be 
    # appended to the front of all above lists.
    # NOTE: the implementation of gerenating time_stamps is temporary.
    pRA, pDEC, timestamp_obs, pointing_type, pRange = generate_pointings(config=config, pointing_filename=config['pointing_file'], data_dir=config['pointing_dir'])

    # Make the main output directories
    make_run_dirs(work_dir=config['work_dir'], run_name=config['run_name'], nPointings=len(pRA), pRange=pRange)

    # Initialize the simulation
    obs = Observation(config=config, Catalog=Catalog, work_dir=config['work_dir'], data_dir=config['data_dir'])
    
    # Run simulation
    obs.runExposure_MPI_PointingList(
        ra_cen=pRA, 
        dec_cen=pDEC, 
        pRange=pRange, 
        timestamp_obs=timestamp_obs,
        pointing_type=pointing_type,
        exptime=config["obs_setting"]["exp_time"],
        use_mpi=config["run_option"]["use_mpi"],
        chips=config["obs_setting"]["run_chips"])

if __name__=='__main__':
    runSim(Catalog=Catalog_example)
    # To run cycle-3 simulation
    # from Catalog.C3Catalog import C3Catalog
    # runSim(Catalog=C3Catalog)
