/*
 * warptoolConfig.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"
#include "warptool.h"

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

    pmConfigReadParamsSet(false);

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

    psTime *time = psTimeGetNow(PS_TIME_TAI);
    psString now = psTimeToISO(time);
    psFree(time);

    // -definerun
    psMetadata *definerunArgs = psMetadataAlloc();
    psMetadataAddStr(definerunArgs, PS_LIST_TAIL, "-mode", 0,
            "define mode (required)", NULL);
    psMetadataAddStr(definerunArgs, PS_LIST_TAIL, "-workdir", 0,
            "define workdir (required)", NULL);
    psMetadataAddStr(definerunArgs, PS_LIST_TAIL, "-registered",  0,
            "time detrend run was registered", now);
    psMetadataAddBool(definerunArgs, PS_LIST_TAIL, "-simple",  0,
            "use the simple output format", false);
 
    // -updaterun
    psMetadata *updaterunArgs = psMetadataAlloc();
    psMetadataAddStr(updaterunArgs, PS_LIST_TAIL, "-warp_id", 0,
            "define warptool ID (required)", NULL);
    psMetadataAddStr(updaterunArgs, PS_LIST_TAIL, "-state", 0,
            "set state (required)", NULL);
#if 0
    psMetadataAddStr(updaterunArgs, PS_LIST_TAIL, "-workdir", 0,
            "define workdir (required)", NULL);
    psMetadataAddStr(updaterunArgs, PS_LIST_TAIL, "-registered",  0,
            "time detrend run was registered", now);
#endif

    // -addinputexp
    psMetadata *addinputexpArgs = psMetadataAlloc();
    psMetadataAddStr(addinputexpArgs, PS_LIST_TAIL, "-warp_id", 0,
            "define warptool ID (required)", NULL);
    psMetadataAddStr(addinputexpArgs, PS_LIST_TAIL, "-cam_id", 0,
            "define camtool ID (required)", NULL);
    psMetadataAddBool(addinputexpArgs, PS_LIST_TAIL, "-magiced",  0,
            "has this exposure been magiced", false);

    // -exp
    psMetadata *expArgs = psMetadataAlloc();
    psMetadataAddStr(expArgs, PS_LIST_TAIL, "-warp_id", 0,
            "search by warptool ID", NULL);
    psMetadataAddStr(expArgs, PS_LIST_TAIL, "-cam_id", 0,
            "search by camtool ID", NULL);
    psMetadataAddU64(expArgs, PS_LIST_TAIL, "-limit",  0,
            "limit result set to N items", 0);
    psMetadataAddBool(expArgs, PS_LIST_TAIL, "-simple",  0,
            "use the simple output format", false);

    // -imfile
    psMetadata *imfileArgs = psMetadataAlloc();
    psMetadataAddStr(imfileArgs, PS_LIST_TAIL, "-warp_id", 0,
            "search by warptool ID", NULL);
    psMetadataAddStr(imfileArgs, PS_LIST_TAIL, "-cam_id", 0,
            "search by camtool ID", NULL);
    psMetadataAddU64(imfileArgs, PS_LIST_TAIL, "-limit",  0,
            "limit result set to N items", 0);
    psMetadataAddBool(imfileArgs, PS_LIST_TAIL, "-simple",  0,
            "use the simple output format", false);

    // -tooverlap
    psMetadata *tooverlapArgs = psMetadataAlloc();
    psMetadataAddStr(tooverlapArgs, PS_LIST_TAIL, "-warp_id", 0,
            "search by warp ID", NULL);
    psMetadataAddU64(tooverlapArgs, PS_LIST_TAIL, "-limit",  0,
            "limit result set to N items", 0);
    psMetadataAddBool(tooverlapArgs, PS_LIST_TAIL, "-simple",  0,
            "use the simple output format", false);

    // -addoverlap
    psMetadata *addoverlapArgs = psMetadataAlloc();
    psMetadataAddStr(addoverlapArgs, PS_LIST_TAIL, "-mapfile", 0,
            "path to skycell <-> imfile mapping file", NULL);

    // -scmap
    psMetadata *scmapArgs = psMetadataAlloc();
    psMetadataAddStr(scmapArgs, PS_LIST_TAIL, "-warp_id", 0,
            "search by warptool ID", NULL);
    psMetadataAddStr(scmapArgs, PS_LIST_TAIL, "-skycell_id", 0,
            "searcy by skycell ID", NULL);
    psMetadataAddStr(scmapArgs, PS_LIST_TAIL, "-tess_id", 0,
            "searcy by tess ID", NULL);
    psMetadataAddU64(scmapArgs, PS_LIST_TAIL, "-limit",  0,
            "limit result set to N items", 0);
    psMetadataAddBool(scmapArgs, PS_LIST_TAIL, "-simple",  0,
            "use the simple output format", false);

    // -towarped
    psMetadata *towarpedArgs = psMetadataAlloc();
    psMetadataAddStr(towarpedArgs, PS_LIST_TAIL, "-warp_id", 0,
            "search by warptool ID", NULL);
    psMetadataAddU64(towarpedArgs, PS_LIST_TAIL, "-limit",  0,
            "limit result set to N items", 0);
    psMetadataAddBool(towarpedArgs, PS_LIST_TAIL, "-simple",  0,
            "use the simple output format", false);
 
    // -addwarped
    psMetadata *addwarpedArgs = psMetadataAlloc();
    psMetadataAddStr(addwarpedArgs, PS_LIST_TAIL, "-warp_id", 0,
            "define warptool ID (required)", NULL);
    psMetadataAddStr(addwarpedArgs, PS_LIST_TAIL, "-skycell_id",  0,
            "define skycell ID (required)", NULL);
    psMetadataAddStr(addwarpedArgs, PS_LIST_TAIL, "-tess_id",  0,
            "define tessellation ID (required)", NULL);
    psMetadataAddStr(addwarpedArgs, PS_LIST_TAIL, "-uri", 0,
            "define URI of file (required)", 0);
    psMetadataAddF64(addwarpedArgs, PS_LIST_TAIL, "-bg",  0,
            "define exposue background", NAN);
    psMetadataAddF64(addwarpedArgs, PS_LIST_TAIL, "-bg_stdev",  0,
            "define exposue background stdev", NAN);
 
    // -warped
    psMetadata *warpedArgs = psMetadataAlloc();
    psMetadataAddStr(warpedArgs, PS_LIST_TAIL, "-warp_id", 0,
            "search by warptool ID", NULL);
    psMetadataAddStr(warpedArgs, PS_LIST_TAIL, "-skycell_id",  0,
            "define skycell ID (required)", NULL);
    psMetadataAddStr(warpedArgs, PS_LIST_TAIL, "-tess_id",  0,
            "define tessellation ID (required)", NULL);
    psMetadataAddStr(warpedArgs, PS_LIST_TAIL, "-exp_tag", 0,
            "define exposure tag (required)", NULL);
    psMetadataAddStr(warpedArgs, PS_LIST_TAIL, "-cam_id", 0,
            "define phase 3 version of exposure tag (required)", NULL);
    psMetadataAddU64(warpedArgs, PS_LIST_TAIL, "-limit",  0,
            "limit result set to N items", 0);
    psMetadataAddBool(warpedArgs, PS_LIST_TAIL, "-simple",  0,
            "use the simple output format", false);

    psFree(now);

#define PXTOOL_MODE(option, modeval, argset) \
{ \
    int N = 0; \
    if ((N = psArgumentGet (argc, argv, option))) { \
        psArgumentRemove (N, &argc, argv); \
        if (config->mode) { \
            psError(PS_ERR_UNKNOWN, true, "only one mode selection is allowed"); \
            psFree(config); \
            return NULL; \
        } \
        config->mode = modeval; \
        config->args = psMemIncrRefCounter(argset); \
    } \
    if (!psMetadataAddMetadata(argSets, PS_LIST_TAIL, option, 0, NULL, argset)) {;\
        psError(PS_ERR_UNKNOWN, false, "failed to add argset for %s", option); \
    } \
    psFree(argset); \
}

    psMetadata *argSets = psMetadataAlloc();
    // find which mode we're running under
    PXTOOL_MODE("-definerun",       WARPTOOL_MODE_DEFINERUN,      definerunArgs);
    PXTOOL_MODE("-updaterun",       WARPTOOL_MODE_UPDATERUN,      updaterunArgs);
    PXTOOL_MODE("-addinputexp",     WARPTOOL_MODE_ADDINPUTEXP,    addinputexpArgs);
    PXTOOL_MODE("-exp",             WARPTOOL_MODE_EXP,            expArgs);
    PXTOOL_MODE("-imfile",          WARPTOOL_MODE_IMFILE,         imfileArgs);
    PXTOOL_MODE("-tooverlap",       WARPTOOL_MODE_TOOVERLAP,      tooverlapArgs);
    PXTOOL_MODE("-addoverlap",      WARPTOOL_MODE_ADDOVERLAP,     addoverlapArgs);
    PXTOOL_MODE("-scmap",           WARPTOOL_MODE_SCMAP,          scmapArgs);
    PXTOOL_MODE("-towarped",        WARPTOOL_MODE_TOWARPED,       towarpedArgs);
    PXTOOL_MODE("-addwarped",       WARPTOOL_MODE_ADDWARPED,      addwarpedArgs);
    PXTOOL_MODE("-warped",          WARPTOOL_MODE_WARPED,         warpedArgs);
#if 0
    PXTOOL_MODE("-tostackedimfile", WARPTOOL_MODE_TOSTACKEDIMFILE, tostackedimfileArgs);
    PXTOOL_MODE("-addstackedimfile", WARPTOOL_MODE_ADDSTACKEDIMFILE, addstackedimfileArgs);
    PXTOOL_MODE("-stackedimfile",   WARPTOOL_MODE_STACKEDIMFILE, stackedimfileArgs);
    PXTOOL_MODE("-todiffimfile", WARPTOOL_MODE_TODIFFIMFILE, todiffimfileArgs);
    PXTOOL_MODE("-adddiffimfile", WARPTOOL_MODE_ADDDIFFIMFILE, adddiffimfileArgs);
    PXTOOL_MODE("-diffimfile",   WARPTOOL_MODE_DIFFIMFILE, diffimfileArgs);
#endif

    bool argErr = false;
    if (config->mode == WARPTOOL_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 Warp Tool\n");
        printf("Usage: %s <mode> [<options>]\n\n", argv[0]);
        printf(" <mode> :\n\n"); 

        psMetadataIterator *iter = psMetadataIteratorAlloc(argSets, 0, NULL);
        psMetadataItem *item = NULL;
        while ((item = psMetadataGetAndIncrement(iter))) {
            if (!item->type == PS_DATA_METADATA) {
                psAbort("all options must be specified as a metadata");
            }

            fprintf(stdout, "%s ", item->name);
            psArgumentHelp(item->data.md);
        }
        psFree(iter);

        psFree(argSets);
        psFree(config);
        return NULL;
    }

    psFree(argSets);

    // setup search criterion
#define addWhereStr(name) \
{ \
    psString str = NULL; \
    bool status = false; \
    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); \
            psFree(config); \
            return NULL; \
        } \
    } \
}

#define addWhereS32(name) \
{ \
    psS32 s32 = 0; \
    bool status = false; \
    if ((s32= psMetadataLookupS32(&status, config->args, "-" #name))) { \
        if (!psMetadataAddS32(config->where, PS_LIST_TAIL, #name, 0, "==", s32)) { \
            psError(PS_ERR_UNKNOWN, false, "failed to add item " #name); \
            psFree(config); \
            return NULL; \
        } \
    } \
}


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

{
    psString str = NULL;
    bool status = false;
    if ((str = psMetadataLookupStr(&status, config->args, "-warp_id"))) {
        if (!psMetadataAddS64(config->where, PS_LIST_TAIL, "warp_id", 0, "==", (psS64)atoll(str))) {
            psError(PS_ERR_UNKNOWN, false, "failed to add item warp_id");
            psFree(config);
            return NULL;
        } 
    } 
}
    addWhereStr(skycell_id);
    addWhereStr(tess_id);
    addWhereStr(exp_tag);

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

    // define Database handle, if used
    // do this last so we don't setup a connection before CLI options are
    // validated
    config->dbh = pmConfigDB(config->modules);
    if (!config->dbh) {
        psError(PS_ERR_UNKNOWN, false, "Can't configure database");
        psFree(config);
        return NULL;
    }

    // save argv/argc
    config->argv = argv;
    config->argc = argc;

    return config;
}
