#!/usr/bin/env python

import argparse
from argparse import RawTextHelpFormatter

import numpy as np

import soxs

descr = (
    "Create a SIMPUT source from an ASCII table of positions and energies. "
    + "The file must contain the total source flux in erg/s/cm**2 on the first line, "
    + "commented with #, and must have three columns of RA (degrees), Dec (degrees), "
    + "and energy (keV) for each event.\n\nExample:\n\n"
    + "# 1.194e-15\n"
    + "30.1  45.5  2.71\n"
    + "29.67 44.95 0.31\n"
    + "31.25 45.03 10.01\n"
    + "29.75 44.44 7.34\n"
    + "30.05 44.01 12.01\n"
    + "31.99 45.21 0.05\n"
    + "..."
)

parser = argparse.ArgumentParser(
    description=descr, formatter_class=RawTextHelpFormatter
)
parser.add_argument(
    "filename",
    type=str,
    help="The filename of the SIMPUT catalog to write or to append to.",
)
parser.add_argument(
    "name", type=str, help="The name of the source in the SIMPUT catalog."
)
parser.add_argument(
    "infile", type=str, help="The file containing the flux and positions and energies."
)
parser.add_argument(
    "--src_filename",
    type=str,
    help="An optional filename to store the source instead of the SIMPUT "
    "catalog file.",
)
parser.add_argument(
    "--append",
    action="store_true",
    help="If set, append a new source an existing SIMPUT catalog. ",
)
parser.add_argument(
    "--overwrite",
    action="store_true",
    help="Overwrite an existing file with the same name.",
)

args = parser.parse_args()

# Read the flux from the first line.
with open(args.infile, "r") as f:
    line = f.readline()
    flux = float(line.split()[-1])

# Now read the positions and energies from the rest.
ra, dec, energy = np.loadtxt(args.infile, unpack=True, skiprows=1)

src = soxs.SimputPhotonList(ra, dec, energy, flux, name=args.name)

if args.append:
    cat = soxs.SimputCatalog.from_file(args.filename)
    cat.append(src, src_filename=args.src_filename, overwrite=args.overwrite)
else:
    cat = soxs.SimputCatalog.from_source(
        args.filename, src, src_filename=args.src_filename, overwrite=args.overwrite
    )
