#!/usr/bin/env python

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals

import os
import sys
import argparse
import pyspextools
from pyspextools.io.ogip import OGIPRegion
from pyspextools.data.badchannels import clean_region

import pyspextools.messages as message

from builtins import int

from future import standard_library

standard_library.install_aliases()


def main():
    """The simres program generates a spo and res file from an input arf and rmf file, and optionally a background
    file. This is particularly useful for simulating spectra for future missions, where the source spectrum file is
    not supplied."""

    # Obtain command line arguments
    parser = simres_arguments()
    args = parser.parse_args()

    # Print message header
    message.print_header(os.path.basename(__file__))

    # Set color in the terminal
    message.set_color(args.color)

    # Load OGIP response files and background spectrum if provided
    ogip = OGIPRegion()

    # Read the background PHA file if specified:
    if args.bkgfile is not None:
        ogip.input_bkg = True
        ogip.read_background_pha(args.bkgfile)
        ogip.back.BackScaling = ogip.back.BackScaling / args.backscale
    else:
        ogip.input_bkg = False
        ogip.back = None

    # Corr spectrum is not used here
    ogip.corr = None

    # Read the response matrix
    ogip.read_rmf(args.rmffile)

    # Read the effective area
    if args.arffile is not None:
        ogip.input_area = True
        ogip.read_arf(args.arffile)
    else:
        ogip.input_area = False
        ogip.area = None

    # Generate dummy spectrum based on rmf channels
    ogip.spec.create_dummy(ogip.resp)

    # Convert spectra and responses to SPEX format
    stat = ogip.add_region(ogip.spec,ogip.resp,back=ogip.back,corr=ogip.corr,area=ogip.area)
    if stat != 0:
        sys.exit()

    # Filter for bad channels (if not blocked by command line argument)
    if args.badchan:
        ogip = clean_region(ogip)

    # Add the simres command to the file history
    history = []
    history.append("SIMRES version: {0}".format(pyspextools.__version__))
    command = ''
    for arg in sys.argv:
        command = command + ' ' + arg
    history.append("Command used: {0}".format(command))
    history.append("Variables derived from commandline:")
    for arg in vars(args):
        line = "{0} : {1}".format(arg, getattr(args,arg))
        history.append(line)

    # Check output file names
    spofile = ogip.spo.check_filename(args.spofile)
    resfile = ogip.res.check_filename(args.resfile)

    # Write output spo and res file
    print("Writing SPO to file: {0}".format(spofile))
    ogip.spo.write_file(spofile,exp_rate=args.exprate,overwrite=args.overwrite,history=history)

    print("Writing RES to file: {0}".format(resfile))
    ogip.res.write_file(resfile,overwrite=args.overwrite,history=history)


# Get command line arguments
def simres_arguments():
    # Obtain command line arguments
    parser = argparse.ArgumentParser(description=message.docs)
    parser.add_argument('--rmffile', help='Input Response matrix (required)', type=str, required=True)
    parser.add_argument('--bkgfile', help='Input Background spectrum', type=str)
    parser.add_argument('--arffile', help='Input Effective area file', type=str)
    parser.add_argument('--spofile', help='Output SPEX spectrum file (.spo, required)', type=str, required=True)
    parser.add_argument('--resfile', help='Output SPEX response file (.res, required)', type=str, required=True)
    parser.add_argument('--keep-badchannels', help='Do not remove bad channels.', dest="badchan", action="store_false",
                        default=True)
    parser.add_argument('--overwrite', help="Overwrite existing spo and res files with same name.", action="store_true",
                        default=False)
    parser.add_argument('--exprate', help="Write additional Exp_Rate column (SPEX >=3.05.00).", action="store_true",
                        default=False)
    parser.add_argument('--backscale', help="Set a background scaling factor.", type=float, default=1.0)
    parser.add_argument('--no-color', help="Suppress color output.", dest="color", action="store_false", default=True)
    parser.add_argument('--version', action='version', version=message.version)

    return parser

if __name__ == "__main__":
    main()
