/*
 * camtoolConfig.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 <math.h>

#include "pxtools.h"
#include "camtool.h"

pxConfig *camtoolConfig(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;
    }

    // -queue
    psMetadata *queueArgs = psMetadataAlloc();
    psMetadataAddStr(queueArgs, PS_LIST_TAIL, "-chip_id",  0,
            "search by chip_id", NULL);
    psMetadataAddStr(queueArgs, PS_LIST_TAIL, "-exp_tag",  0,
            "search by exp_tag", NULL);
    psMetadataAddStr(queueArgs, PS_LIST_TAIL, "-exp_id",  0,
            "search by exp_id", NULL);
    psMetadataAddStr(queueArgs, PS_LIST_TAIL, "-inst",  0,
            "search by camera", NULL);
    psMetadataAddStr(queueArgs, PS_LIST_TAIL, "-telescope",  0,
            "search by telescope", NULL);
    psMetadataAddStr(queueArgs, PS_LIST_TAIL, "-dateobs",  0,
            "search by observation time", NULL);
    psMetadataAddStr(queueArgs, PS_LIST_TAIL, "-exp_type",  0,
            "search by exposure type", NULL);
    psMetadataAddStr(queueArgs, PS_LIST_TAIL, "-imfiles",  0,
            "search by number of imfiles", NULL);
    psMetadataAddStr(queueArgs, PS_LIST_TAIL, "-workdir",  0,
            "search by workdir", NULL);
    psMetadataAddStr(queueArgs, PS_LIST_TAIL, "-filter",  0,
            "search by filter ", NULL);
    psMetadataAddF32(queueArgs, PS_LIST_TAIL, "-airmass",  0,
            "search by airmass", NAN);
    psMetadataAddF64(queueArgs, PS_LIST_TAIL, "-ra",  0,
            "search by RA", NAN);
    psMetadataAddF64(queueArgs, PS_LIST_TAIL, "-decl",  0,
            "search by DEC", NAN);
    psMetadataAddF32(queueArgs, PS_LIST_TAIL, "-exp_time",  0,
            "search by exposure time", NAN);
    psMetadataAddF64(queueArgs, PS_LIST_TAIL, "-bg",  0,
            "search by exposue background", NAN);
    psMetadataAddF64(queueArgs, PS_LIST_TAIL, "-bg_stdev",  0,
            "search by exposue background stdev", NAN);
    psMetadataAddF64(queueArgs, PS_LIST_TAIL, "-bg_mean_stdev",  0,
            "search by exposue background mean stdev", NAN);
    psMetadataAddF64(queueArgs, PS_LIST_TAIL, "-alt",  0,
            "search by altitute", NAN);
    psMetadataAddF64(queueArgs, PS_LIST_TAIL, "-az",  0,
            "search by azimuth", NAN);
    psMetadataAddF32(queueArgs, PS_LIST_TAIL, "-ccd_temp",  0,
            "search by ccd tempature", NAN);
    psMetadataAddF64(queueArgs, PS_LIST_TAIL, "-posang",  0,
            "search by rotator position angle", NAN);
    psMetadataAddStr(queueArgs, PS_LIST_TAIL, "-object",  0,
            "search by exposure object", NULL);
    psMetadataAddStr(queueArgs, PS_LIST_TAIL, "-set_workdir",  0,
            "define workdir", NULL);
    psMetadataAddStr(queueArgs, PS_LIST_TAIL, "-set_label",  0,
            "define label", NULL);
    psMetadataAddStr(queueArgs, PS_LIST_TAIL, "-set_recipe",  0,
            "define recipe", NULL);
    psMetadataAddStr(queueArgs, PS_LIST_TAIL, "-set_expgroup",  0,
            "define exposure group", NULL);
    psMetadataAddStr(queueArgs, PS_LIST_TAIL, "-set_dvodb",  0,
            "define DVO db", NULL);

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

    
    // -pendingimfile
    psMetadata *pendingimfileArgs = psMetadataAlloc();
    psMetadataAddStr(pendingimfileArgs, PS_LIST_TAIL, "-cam_id", 0,
            "search by camtool ID", NULL);
    psMetadataAddStr(pendingimfileArgs, PS_LIST_TAIL, "-chip_id", 0,
            "search by chiptool ID", NULL);
    psMetadataAddStr(pendingimfileArgs, PS_LIST_TAIL, "-class", 0,
            "search by class", NULL);
    psMetadataAddStr(pendingimfileArgs, PS_LIST_TAIL, "-class_id", 0,
            "search by class ID", NULL);
    psMetadataAddBool(pendingimfileArgs, PS_LIST_TAIL, "-simple", 0,
            "use the simple output format", false);


    // -addprocessedexp
    psMetadata *addprocessedexpArgs = psMetadataAlloc();
    psMetadataAddStr(addprocessedexpArgs, PS_LIST_TAIL, "-cam_id", 0,
            "define camtool ID (required)", NULL);
    psMetadataAddStr(addprocessedexpArgs, PS_LIST_TAIL, "-chip_id", 0,
            "define chiptool ID (required)", NULL);
    psMetadataAddStr(addprocessedexpArgs, PS_LIST_TAIL, "-uri", 0,
            "define URI (required)", NULL);
    psMetadataAddF64(addprocessedexpArgs, PS_LIST_TAIL, "-bg", 0,
            "define exposue background (required)", NAN);
    psMetadataAddF64(addprocessedexpArgs, PS_LIST_TAIL, "-bg_stdev", 0,
            "define exposue background stdev (required)", NAN);
    psMetadataAddF64(addprocessedexpArgs, PS_LIST_TAIL, "-bg_mean_stdev", 0,
            "define exposue background mean stdev (required)", NAN);
    psMetadataAddF32(addprocessedexpArgs, PS_LIST_TAIL, "-sigma_ra", 0,
            "define exposure E ra (required)", NAN);
    psMetadataAddF32(addprocessedexpArgs, PS_LIST_TAIL, "-sigma_dec", 0,
            "define exposure E dec (required)", NAN);
    psMetadataAddS32(addprocessedexpArgs, PS_LIST_TAIL, "-nastro", 0,
            "define number of objects (required)", -1);
    psMetadataAddF32(addprocessedexpArgs, PS_LIST_TAIL, "-zp_mean", 0,
            "define zero point mean (required)", NAN);
    psMetadataAddF32(addprocessedexpArgs, PS_LIST_TAIL, "-zp_stdev", 0,
            "define zero point stdev (required)", NAN);
    psMetadataAddStr(addprocessedexpArgs, PS_LIST_TAIL, "-path_base", 0,
            "define banana 1", NULL);
    psMetadataAddS16(addprocessedexpArgs, PS_LIST_TAIL, "-code",  0,
            "set fault code (required)", 0);
    psMetadataAddBool(addprocessedexpArgs, PS_LIST_TAIL, "-faulted",  0,
            "only return imfiles with a fault status set", false);

    // -processedexp
    psMetadata *processedexpArgs = psMetadataAlloc();
    psMetadataAddStr(processedexpArgs, PS_LIST_TAIL, "-cam_id", 0,
            "search by camtool ID", NULL);
    psMetadataAddStr(processedexpArgs, PS_LIST_TAIL, "-chip_id", 0,
            "search by chiptool ID", NULL);
    psMetadataAddU64(processedexpArgs, PS_LIST_TAIL, "-limit",  0,
            "limit result set to N items", 0);
    psMetadataAddBool(processedexpArgs, PS_LIST_TAIL, "-simple", 0,
            "use the simple output format", false);
    psMetadataAddBool(processedexpArgs, PS_LIST_TAIL, "-faulted",  0,
            "only return imfiles with a fault status set", false);

    // -updateprocessedexp
    psMetadata *updateprocessedexpArgs = psMetadataAlloc();
    psMetadataAddStr(updateprocessedexpArgs, PS_LIST_TAIL, "-cam_id", 0,
            "search by camtool ID", NULL);
    psMetadataAddStr(updateprocessedexpArgs, PS_LIST_TAIL, "-chip_id",  0,
            "search by chiptool ID", NULL);
    psMetadataAddStr(updateprocessedexpArgs, PS_LIST_TAIL, "-class",  0,
            "search by class", NULL);
    psMetadataAddStr(updateprocessedexpArgs, PS_LIST_TAIL, "-class_id",  0,
            "search by class ID", NULL);
    psMetadataAddS16(updateprocessedexpArgs, PS_LIST_TAIL, "-code",  0,
            "set fault code (required)", 0);

    // -block
    psMetadata *blockArgs = psMetadataAlloc();
    psMetadataAddStr(blockArgs, PS_LIST_TAIL, "-label",  0,
            "name of a label to mask out", NULL);
    
    // -masked
    psMetadata *maskedArgs = psMetadataAlloc();
    psMetadataAddBool(maskedArgs, PS_LIST_TAIL, "-simple",  0,
            "use the simple output format", false);
    
    // -unblock
    psMetadata *unblockArgs = psMetadataAlloc();
    psMetadataAddStr(unblockArgs, PS_LIST_TAIL, "-label",  0,
            "name of a label to unmask", NULL);

#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("-queue",           CAMTOOL_MODE_QUEUE,         queueArgs);
    PXTOOL_MODE("-pendingexp",      CAMTOOL_MODE_PENDINGEXP,    pendingexpArgs);
    PXTOOL_MODE("-pendingimfile",CAMTOOL_MODE_PENDINGIMFILE, pendingimfileArgs);
    PXTOOL_MODE("-addprocessedexp", CAMTOOL_MODE_ADDPROCESSEDEXP, addprocessedexpArgs);
    PXTOOL_MODE("-processedexp", CAMTOOL_MODE_PROCESSEDEXP,  processedexpArgs);
    PXTOOL_MODE("-updateprocessedexp", CAMTOOL_MODE_UPDATEPROCESSEDEXP,updateprocessedexpArgs);
    PXTOOL_MODE("-block",           CAMTOOL_MODE_BLOCK,         blockArgs);
    PXTOOL_MODE("-masked",          CAMTOOL_MODE_MASKED,        maskedArgs);
    PXTOOL_MODE("-unblock",         CAMTOOL_MODE_UNBLOCK,       unblockArgs);

    bool argErr = false;
    if (config->mode == CAMTOOL_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 Camera 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; \
        } \
    } \
}

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

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

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

    // convert '-inst' to 'camera'
    {
        psString str = NULL; 
        bool status = false;
        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");
                psFree(config);
                return NULL;
            }
        }
    }
    addWhereStr(telescope);
    addWhereStr(exp_type);
    {
        int imfiles = 0; 
        bool status = false;
        if ((imfiles = psMetadataLookupS32(&status, config->args, "-imfiles"))) {
            if (!psMetadataAddS32(config->where, PS_LIST_TAIL, "imfiles", 0, "==", imfiles)) {
                psError(PS_ERR_UNKNOWN, false, "failed to add item imfiles");
                psFree(config);
                return NULL;
            }
        }
    }
    addWhereStr(class);
    addWhereStr(class_id);
    addWhereStr(filter);

    if (psListLength(config->where->list) < 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");
        psFree(config);
        return NULL;
    }

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

    return config;
}
