/*
 * guidetoolConfig.c
 *
 * Copyright (C) 2006  Joshua Hoblitt
 *
 * 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; version 2 of the License.
 *
 * 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
 * program; see the file COPYING. If not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 */

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

#include <psmodules.h>

#include "pxtools.h"

// this function can not fail -- exits on error

pxConfig *guidetoolConfig(pxConfig *config, int argc, char **argv) {
    if (!config) {
        config = pxConfigAlloc();
    }

    pmConfigReadParamsSet(false);

    // setup site config
    config->modules = pmConfigRead(&argc, argv);
    if (!config->modules) {
        psError(PS_ERR_UNKNOWN, false, "Can't find site configuration");
        exit(EXIT_FAILURE);
    }

    // CLI options
    // modes
    psMetadata *args = psMetadataAlloc();
    psMetadataAddStr(args , PS_LIST_TAIL, "-pending", 0,
        "examine pending image table, write ppImage output", NULL);
    psMetadataAddStr(args , PS_LIST_TAIL, "-define",  0,
        "update pending image table", NULL);

    // -pending search
    psMetadata *pendingArgs = psMetadataAlloc();
    psMetadataAddStr(pendingArgs, PS_LIST_TAIL, "-exp_id",  0,
        "define exposure ID", NULL);
    psMetadataAddStr(pendingArgs, PS_LIST_TAIL, "-inst",  0,
        "define camera of interest", NULL);
    psMetadataAddStr(pendingArgs, PS_LIST_TAIL, "-telescope",  0,
        "define telescope of interest", NULL);
    psMetadataAddStr(pendingArgs, PS_LIST_TAIL, "-exp_type",  0,
        "define exposure type", NULL);
    psMetadataAddS32(pendingArgs, PS_LIST_TAIL, "-imfiles",  0,
        "define number of imfiles", 0);
    psMetadataAddStr(pendingArgs, PS_LIST_TAIL, "-filter",  0,
        "define filter of interest", NULL);
    psMetadataAddStr(pendingArgs, PS_LIST_TAIL, "-recipe",  0,
        "define recipe of interest", NULL);
    psMetadataAddS32(pendingArgs, PS_LIST_TAIL, "-guide_version",  0,
        "define guide_version of interest", 0);

    // -define inputs
    psMetadata *defineArgs = psMetadataAlloc();
    psMetadataAddStr(defineArgs, PS_LIST_TAIL, "-exp_id",  0,
        "define class", NULL);
    psMetadataAddStr(defineArgs, PS_LIST_TAIL, "-inst",  0,
        "define camera of interest", NULL);
    psMetadataAddStr(defineArgs, PS_LIST_TAIL, "-telescope",  0,
        "define camera of interest", NULL);
    psMetadataAddStr(defineArgs, PS_LIST_TAIL, "-exp_type",  0,
        "define class", NULL);
    psMetadataAddS32(defineArgs, PS_LIST_TAIL, "-imfiles",  0,
        "define number of imfiles", 0);
    psMetadataAddStr(defineArgs, PS_LIST_TAIL, "-filter",  0,
        "define filter of interest", NULL);
    // these two are inputs NOT search parameters
    psMetadataAddStr(defineArgs, PS_LIST_TAIL, "-recipe",  0,
        "define recipe of interest", NULL);
    psMetadataAddS32(defineArgs, PS_LIST_TAIL, "-guide_version",  0,
        "define guide_version of interest", 0);

    // find which mode we're running under
    int N = 0;
    config->mode = PX_MODE_NONE;
    if ((N = psArgumentGet (argc, argv, "-pending"))) {
        psArgumentRemove (N, &argc, argv);
        if (config->mode) {
            psError(PS_ERR_UNKNOWN, true, "only one mode selection is allowed");
        }
        config->mode = PX_MODE_PENDING;
    }
    if ((N = psArgumentGet (argc, argv, "-define"))) {
        psArgumentRemove (N, &argc, argv);
        if (config->mode) {
            psError(PS_ERR_UNKNOWN, true, "only one mode selection is allowed");
        }
        config->mode = PX_MODE_DEFINE;
    }

    // parse CLI for these options
    switch (config->mode) {
        case PX_MODE_PENDING:
            config->args = psMemIncrRefCounter(pendingArgs);
            break;
        case PX_MODE_DEFINE:
            config->args = psMemIncrRefCounter(defineArgs);
            break;
        default:
            config->args = psMemIncrRefCounter(args);
    }

    bool argErr = false;
    if (config->mode == PX_MODE_NONE) {
        argErr = true;
        fprintf (stderr, "mode argument is required\n");
    } else if (! psArgumentParse(config->args, &argc, argv) || argc != 1) {
        argErr = true;
        fprintf (stderr, "error parsing arguments\n");
    }

    if (argErr) {
        printf("\nPan-STARRS Guide Star Tool\n");
        printf("Usage: %s <mode> [<options>]\n\n", argv[0]);
        printf(" <mode> : -pending | -define\n\n");
        fprintf (stdout, "-pending ");
        psArgumentHelp(pendingArgs);
        fprintf (stdout, "-define ");
        psArgumentHelp(defineArgs);
        psFree(args);
        psFree(pendingArgs);
        psFree(defineArgs);
        exit(EXIT_FAILURE);
    }

    psFree(args);
    psFree(pendingArgs);
    psFree(defineArgs);

    // setup search criterion
#define addWhereStr(name) \
    if ((str = psMetadataLookupStr(&status, config->args, "-" #name))) { \
        if (!psMetadataAddStr(config->where, PS_LIST_TAIL, #name, 0, "==", str)) {\
            psError(PS_ERR_UNKNOWN, false, "failed to add item " #name); \
            exit(EXIT_FAILURE); \
        } \
    }

    // generate SQL where clause
    config->where = psMetadataAlloc();

{
    psString str = NULL;
    int n = 0;
    bool status = false;

    addWhereStr(exp_id);
    // convert '-inst' to 'camera'
    if ((str = psMetadataLookupStr(&status, config->args, "-inst"))) {
        if (!psMetadataAddStr(config->where, PS_LIST_TAIL, "camera", 0, "==", str)) {
            psError(PS_ERR_UNKNOWN, false, "failed to add item camera");
            exit(EXIT_FAILURE);
        }
    }
    addWhereStr(telescope);
    addWhereStr(exp_type);
    if ((n = psMetadataLookupS32(&status, config->args, "-imfiles"))) {
        if (!psMetadataAddS32(config->where, PS_LIST_TAIL, "imfiles", 0, "==", n)) {
            psError(PS_ERR_UNKNOWN, false, "failed to add item imfiles");
            exit(EXIT_FAILURE);
        }
    }
    addWhereStr(filter);
    addWhereStr(stats);
    addWhereStr(recipe);
    if ((n = psMetadataLookupS32(&status, config->args, "-guide_version"))) {
        if (!psMetadataAddS32(config->where, PS_LIST_TAIL, "guide_version", 0, "==", n)) {
            psError(PS_ERR_UNKNOWN, false, "failed to add item guide_version");
            exit(EXIT_FAILURE);
        }
    }
}

    if (config->where->list->n < 1) {
        psFree(config->where);
        config->where = NULL;
    }

    // define Database handle, if used
    config->dbh = pmConfigDB(config->modules);
    if (!config->dbh) {
        psError(PS_ERR_UNKNOWN, false, "Can't configure database");
        exit(EXIT_FAILURE);
    }

    return config;
}
