#!/usr/bin/env python2.7

# HTTM: A transformation library for RAW and Electron Flux TESS Images
# Copyright (C) 2016, 2017 John Doty and Matthew Wampler-Doty of Noqsi Aerospace, Ltd.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.


import argparse
import logging
import os
import sys

import pkg_resources

from httm import raw_fits_to_calibrated
from httm.data_structures.raw_converter import raw_converter_parameters, raw_transformation_flags
from httm.system.command_line import add_arguments_from_settings
from httm.system.config_file import parse_config
from httm.transformations.raw_converters_to_calibrated import raw_transformations

log_level = os.getenv('LOG', 'WARNING').upper()
logging.basicConfig(
    format="[%(asctime)s] %(levelname)s [%(name)s.%(funcName)s:%(lineno)d] %(message)s"
    if log_level == "DEBUG" else "%(levelname)s %(message)s",
    datefmt="%H:%M:%S",
    level=getattr(logging, log_level))

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='Transform a RAW FITS file into a Calibrated FITS file')

    parser.add_argument('input', type=str, help="The name of the RAW FITS file to use as input")
    parser.add_argument('output', type=str, help="The name of the Calibrated FITS file to use as output")

    parser.add_argument('--version', action='version', version=pkg_resources.get_distribution("httm").version)

    parser.add_argument('--config', default=None, type=str, dest='config',
                        help='Set an optional configuration file')
    add_arguments_from_settings(parser, raw_transformation_flags)
    add_arguments_from_settings(parser, raw_transformations)
    add_arguments_from_settings(parser, raw_converter_parameters)

    args = parser.parse_args()
    settings = parse_config(args.config, [raw_transformation_flags,
                                          raw_transformations,
                                          raw_converter_parameters],
                            override=args) if args.config is not None else args
    raw_fits_to_calibrated(args.input,
                           args.output,
                           command=" ".join(sys.argv),
                           flag_overrides=settings,
                           parameter_overrides=settings,
                           transformation_settings=settings)
