/*
 * difftoolConfig.c
 *
 * Copyright (C) 2007  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 "difftool.h"

pxConfig *difftoolConfig(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, "-workdir", 0,
            "define workdir (required)", NULL);
    psMetadataAddStr(definerunArgs, PS_LIST_TAIL, "-registered",  0,
            "time detrend run was registered", now);
    psMetadataAddStr(definerunArgs, PS_LIST_TAIL, "-skycell_id",  0,
            "define skycell ID (required)", NULL);
    psMetadataAddStr(definerunArgs, PS_LIST_TAIL, "-tess_id",  0,
            "define tessellation ID (required)", NULL);
    psMetadataAddBool(definerunArgs, PS_LIST_TAIL, "-simple",  0,
            "use the simple output format", false);

    // -updaterun
    psMetadata *updaterunArgs = psMetadataAlloc();
    psMetadataAddStr(updaterunArgs, PS_LIST_TAIL, "-diff_id", 0,
            "define diff 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

    // -addinputskyfile
    psMetadata *addinputskyfileArgs = psMetadataAlloc();
    psMetadataAddStr(addinputskyfileArgs, PS_LIST_TAIL, "-diff_id", 0,
            "define diff ID (required)", NULL);
    psMetadataAddStr(addinputskyfileArgs, PS_LIST_TAIL, "-warp_id", 0,
            "define warp ID", NULL);
    psMetadataAddStr(addinputskyfileArgs, PS_LIST_TAIL, "-stack_id", 0,
            "define stack ID)", NULL);
    psMetadataAddStr(addinputskyfileArgs, PS_LIST_TAIL, "-kind", 0,
            "define kind", NULL);
    psMetadataAddBool(addinputskyfileArgs, PS_LIST_TAIL, "-template",  0,
            "this sky cell file is the subtrahend", false);

    // -inputskyfile
    psMetadata *inputskyfileArgs = psMetadataAlloc();
    psMetadataAddStr(inputskyfileArgs, PS_LIST_TAIL, "-diff_id", 0,
            "search by diff ID", NULL);
    psMetadataAddStr(inputskyfileArgs, PS_LIST_TAIL, "-warp_id", 0,
            "search by warp ID", NULL);
    psMetadataAddStr(inputskyfileArgs, PS_LIST_TAIL, "-skycell_id", 0,
            "search by skycell ID", NULL);
    psMetadataAddStr(inputskyfileArgs, PS_LIST_TAIL, "-tess_id", 0,
            "search by tess ID", NULL);
    psMetadataAddStr(inputskyfileArgs, PS_LIST_TAIL, "-kind", 0,
            "search by kind", NULL);
    psMetadataAddBool(inputskyfileArgs, PS_LIST_TAIL, "-template",  0,
            "search by subtrahend", false);
    psMetadataAddU64(inputskyfileArgs, PS_LIST_TAIL, "-limit",  0,
            "limit result set to N items", 0);
    psMetadataAddBool(inputskyfileArgs, PS_LIST_TAIL, "-simple",  0,
            "use the simple output format", false);

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

    // -adddiffskyfile
    psMetadata *adddiffskyfileArgs = psMetadataAlloc();
    psMetadataAddStr(adddiffskyfileArgs, PS_LIST_TAIL, "-diff_id", 0,
            "define warp ID (required)", NULL);
    psMetadataAddStr(adddiffskyfileArgs, PS_LIST_TAIL, "-uri", 0,
            "define URI of file", 0);
    psMetadataAddStr(adddiffskyfileArgs, PS_LIST_TAIL, "-path_base", 0,
            "define base output location", 0);
    psMetadataAddF64(adddiffskyfileArgs, PS_LIST_TAIL, "-bg",  0,
            "define exposure background", NAN);
    psMetadataAddF64(adddiffskyfileArgs, PS_LIST_TAIL, "-bg_stdev",  0,
            "define exposure background mean stdev", NAN);
    psMetadataAddS16(adddiffskyfileArgs, PS_LIST_TAIL, "-code",  0,
            "set fault code", 0);

    // -diffskyfile
    psMetadata *diffskyfileArgs = psMetadataAlloc();
    psMetadataAddStr(diffskyfileArgs, PS_LIST_TAIL, "-diff_id", 0,
            "search by warp ID", NULL);
    psMetadataAddStr(diffskyfileArgs , PS_LIST_TAIL, "-skycell_id",  0,
            "define skycell ID", NULL);
    psMetadataAddStr(diffskyfileArgs, PS_LIST_TAIL, "-tess_id",  0,
            "define tessellation ID", NULL);
    psMetadataAddU64(diffskyfileArgs, PS_LIST_TAIL, "-limit",  0,
            "limit result set to N items", 0);
    psMetadataAddBool(diffskyfileArgs, PS_LIST_TAIL, "-simple",  0,
            "use the simple output format", false);

    // -revertdiffskyfile
    psMetadata *revertdiffskyfileArgs = psMetadataAlloc();
    psMetadataAddStr(revertdiffskyfileArgs, PS_LIST_TAIL, "-diff_id", 0,
            "define warp ID (required)", NULL);
    psMetadataAddS16(revertdiffskyfileArgs, PS_LIST_TAIL, "-code",  0,
            "search by fault code", 0);

    psFree(now);

    psMetadata *argSets = psMetadataAlloc();
    psMetadata *modes = psMetadataAlloc();

    PXTOOL_ADD_MODE("-definerun",       "",     DIFFTOOL_MODE_DEFINERUN,      definerunArgs);
    PXTOOL_ADD_MODE("-updaterun",       "",     DIFFTOOL_MODE_UPDATERUN,      updaterunArgs);
    PXTOOL_ADD_MODE("-addinputskyfile", "",     DIFFTOOL_MODE_ADDINPUTSKYFILE, addinputskyfileArgs);
    PXTOOL_ADD_MODE("-inputskyfile",    "",     DIFFTOOL_MODE_INPUTSKYFILE,    inputskyfileArgs);
    PXTOOL_ADD_MODE("-todiffskyfile",   "",     DIFFTOOL_MODE_TODIFFSKYFILE,   todiffskyfileArgs);
    PXTOOL_ADD_MODE("-adddiffskyfile",  "",     DIFFTOOL_MODE_ADDDIFFSKYFILE,  adddiffskyfileArgs);
    PXTOOL_ADD_MODE("-diffskyfile",     "",     DIFFTOOL_MODE_DIFFSKYFILE,     diffskyfileArgs);
    PXTOOL_ADD_MODE("-revertdiffskyfile","",    DIFFTOOL_MODE_REVERTDIFFSKYFILE,     revertdiffskyfileArgs);

    if (!pxGetOptions(stderr, argc, argv, config, modes, argSets)) {
        psError(PS_ERR_UNKNOWN, true, "option parsing failed");
        psFree(argSets);
        psFree(modes);
        psFree(config);
        return NULL;
    }

    psFree(argSets);
    psFree(modes);

    // 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, "-diff_id"))) {
        if (!psMetadataAddS64(config->where, PS_LIST_TAIL, "diff_id", 0, "==", (psS64)atoll(str))) {
            psError(PS_ERR_UNKNOWN, false, "failed to add item diff_id");
            psFree(config);
            return NULL;
        }
    }
}
{
    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);

    // convert '-code' to 'fault'
    {
        psS16 fault = 0;
        bool status = false;
        if ((fault = psMetadataLookupS16(&status, config->args, "-code"))) {
            if (!psMetadataAddS16(config->where, PS_LIST_TAIL, "fault", 0, "==", fault)) {
                psError(PS_ERR_UNKNOWN, false, "failed to add item fault");
                psFree(config);
                return NULL;
            }
        }
    }

    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;
    }

    return config;
}
