#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <stdio.h>
#include <pslib.h>
#include <psmodules.h>
#include <string.h>

#include "ppStats.h"
#include "ppStatsData.h"
#include "ppStatsSetupFromArgs.h"

// This file is for setting up the required inputs from the command-line

// Print usage information and die
static void usageAndDie(pmConfig *config      // Configuration (contains the arguments list)
    )
{
    printf("Return headers, concepts and/or image statistics.\n\n"
           "Usage:\n"
           "\t%s INPUT.fits [OUTPUT_NAME]\n"
           "\n", config->argv[0]);
    psArgumentHelp(config->arguments);
    psFree(config);
    psLibFinalize();
    pmConceptsDone();
    pmConfigDone();
    exit(EXIT_FAILURE);
}

// Generate a list from the arguments
static void listFromArguments(psMetadata *arguments, // Arguments to parse
                              const char *name, // Name of the item, for error message
                              const char *flag, // The flag for the argument of interest
                              psList *target // The target list
    )
{
    psString regex = NULL;              // Regular expression for the flag
    psStringAppend(&regex, "^%s$", flag);
    psMetadataIterator *iterator = psMetadataIteratorAlloc(arguments, PS_LIST_HEAD, regex); // Iterator
    psFree(regex);
    psMetadataItem *item;               // Item from iteration
    while ((item = psMetadataGetAndIncrement(iterator))) {
        if (item->type != PS_DATA_STRING) {
            psLogMsg(__func__, PS_LOG_WARN, "%s name is not of type STRING (%x) --- ignored.\n",
                     name, item->type);
            continue;
        }
        if (item->data.V && strlen(item->data.V) > 0) {
            psListAdd(target, PS_LIST_TAIL, item->data.V);
        }
    }
    psFree(iterator);

    return;
}

// Set the statistics option; for arguments
static inline void statsOptionArguments(psMetadata *arguments, // Arguments to parse
                                        const char *name, // Name for option
                                        ppStatsData *data, // Configuration data
                                        psStatsOptions option // Option to check for
    )
{
    if (psMetadataLookupBool(NULL, arguments, name)) {
        data->stats->options |= option;
        data->doStats = true;
    }
    return;
}

// Print out what we're going to do, from the list
static void checkList(psList *list,     // List
                      const char *name  // Name of list
    )
{
    psString value;
    psListIterator *iterator = psListIteratorAlloc(list, PS_LIST_HEAD, false);
    while ((value = psListGetAndIncrement(iterator))) {
        printf("%s: %s\n", name, value);
    }
    psFree(iterator);
    return;
}


ppStatsData *ppStatsSetupFromArgs(pmConfig *config // Configuration
    )
{
    // Setup and parse command-line arguments
    psMetadata *arguments = config->arguments; // Arguments
    psMetadataAddStr(arguments, PS_LIST_TAIL, "-chip", PS_META_DUPLICATE_OK, "Chip to inspect", NULL);
    psMetadataAddStr(arguments, PS_LIST_TAIL, "-cell", PS_META_DUPLICATE_OK, "Cell to inspect", NULL);
    psMetadataAddStr(arguments, PS_LIST_TAIL, "-header", PS_META_DUPLICATE_OK, "Header to look up", NULL);
    psMetadataAddStr(arguments, PS_LIST_TAIL, "-concept", PS_META_DUPLICATE_OK, "Concept to look up", NULL);
    psMetadataAddBool(arguments, PS_LIST_TAIL, "-mean", 0, "Calculate sample mean", false);
    psMetadataAddBool(arguments, PS_LIST_TAIL, "-stdev", 0, "Calculate sample standard deviation", false);
    psMetadataAddBool(arguments, PS_LIST_TAIL, "-median", 0, "Calculate sample median", false);
    psMetadataAddBool(arguments, PS_LIST_TAIL, "-quartile", 0, "Calculate sample quartiles", false);
    psMetadataAddBool(arguments, PS_LIST_TAIL, "-robust-median", 0, "Calculate robust median", false);
    psMetadataAddBool(arguments, PS_LIST_TAIL, "-robust-stdev", 0, "Calculate robust standard deviation", false);
    psMetadataAddBool(arguments, PS_LIST_TAIL, "-robust-quartile", 0, "Calculate robust quartile range", false);
    psMetadataAddBool(arguments, PS_LIST_TAIL, "-fitted-mean", 0, "Calculate fitted mean", false);
    psMetadataAddBool(arguments, PS_LIST_TAIL, "-fitted-stdev", 0, "Calculate fitted standard deviation", false);
    psMetadataAddBool(arguments, PS_LIST_TAIL, "-clipped-mean", 0, "Calculate clipped median", false);
    psMetadataAddBool(arguments, PS_LIST_TAIL, "-clipped-stdev", 0, "Calculate clipped standard deviation", false);
    psMetadataAddS32(arguments, PS_LIST_TAIL, "-iter", 0, "Clipping iterations", 0);
    psMetadataAddF32(arguments, PS_LIST_TAIL, "-rej", 0, "Clipping level", 0.0);
    psMetadataAddF32(arguments, PS_LIST_TAIL, "-sample", 0, "Sampling fraction", 0.0);

    if (*config->argc == 1) {
        // No command-line arguments: print the help
        usageAndDie(config);
    }
    if (!psArgumentParse(arguments, config->argc, config->argv) ||
        (*config->argc != 2 && *config->argc != 3)) {
        printf("Unable to parse command-line arguments.\n\n");
        usageAndDie(config);
    }

    // Parse the command-line options
    ppStatsData *data = ppStatsDataAlloc(); // The data
    const char *inName = config->argv[1]; // Input file name
    psArgumentRemove(1, config->argc, config->argv);

    listFromArguments(arguments, "Chip", "-chip", data->chips);
    listFromArguments(arguments, "Cell", "-cell", data->cells);
    listFromArguments(arguments, "Header", "-header", data->headers);
    listFromArguments(arguments, "Concept", "-concept", data->concepts);

    // Set the statistics options
    statsOptionArguments(arguments, "-mean", data,     PS_STAT_SAMPLE_MEAN);
    statsOptionArguments(arguments, "-stdev", data,    PS_STAT_SAMPLE_STDEV);
    statsOptionArguments(arguments, "-median", data,   PS_STAT_SAMPLE_MEDIAN);
    statsOptionArguments(arguments, "-quartile", data, PS_STAT_SAMPLE_QUARTILE);
    statsOptionArguments(arguments, "-robust-median", data,   PS_STAT_ROBUST_MEDIAN);
    statsOptionArguments(arguments, "-robust-stdev", data,    PS_STAT_ROBUST_STDEV);
    statsOptionArguments(arguments, "-robust-quartile", data, PS_STAT_ROBUST_QUARTILE);
    statsOptionArguments(arguments, "-fitted-mean", data,   PS_STAT_FITTED_MEAN);
    statsOptionArguments(arguments, "-fitted-stdev", data,  PS_STAT_FITTED_STDEV);
    statsOptionArguments(arguments, "-clipped-mean", data,  PS_STAT_CLIPPED_MEAN);
    statsOptionArguments(arguments, "-clipped-stdev", data, PS_STAT_CLIPPED_STDEV);
    data->stats->clipSigma = psMetadataLookupF32(NULL, arguments, "-rej");
    data->stats->clipIter = psMetadataLookupS32(NULL, arguments, "-iter");
    data->sample = psMetadataLookupF32(NULL, arguments, "-sample");


    // Open the input file, determine the camera
    {
        data->fits = psFitsOpen(inName, "r");
        if (!data->fits) {
            psError(PS_ERR_IO, false, "Unable to open input file %s\n", inName);
            goto die;
        }
        psMetadata *header = psFitsReadHeader(NULL, data->fits); // The FITS (primary) header
        psMetadata *format = pmConfigCameraFormatFromHeader(config, header);
        if (!format) {
            psError(PS_ERR_UNKNOWN, false, "Unable to determine camera format for %s\n", inName);
            psFree(header);
            goto die;
        }
        data->fpa = pmFPAConstruct(config->camera);
        if (!data->fpa) {
            psError(PS_ERR_UNKNOWN, false, "Unable to construct FPA for %s\n", inName);
            psFree(header);
            psFree(format);
            goto die;
        }
        pmFPAview *view = pmFPAAddSourceFromHeader(data->fpa, header, format);
        psFree(header);
        psFree(format);
        if (!view) {
            psError(PS_ERR_UNKNOWN, false, "Unable to add input file %s to FPA.\n", inName);
            goto die;
        }
        psFree(view);
    }

    // Get the rest from the recipe
    ppStatsSetupFromRecipe(data, config);

    // Print out what we're going to do
    if (psTraceGetLevel("ppStats") > 9) {
        checkList(data->chips, "CHIP");
        checkList(data->cells, "CELL");
        checkList(data->headers, "HEADER");
        checkList(data->concepts, "CONCEPT");
    }

    return data;

    // Common path for error conditions: clean up and exit.
die:
    psErrorStackPrint (stderr, "failure in %s", __func__);
    psFree(config);
    psFree(data);
    pmConceptsDone();
    pmConfigDone();
    psLibFinalize();
    exit(EXIT_FAILURE);
}
