/*
 * chiptoolConfig.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 <stdint.h>

#include <psmodules.h>

#include "pxtools.h"
#include "chiptool.h"

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

    pmConfigReadParamsSet(false);

    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, "-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);

    // XXX EAM : are these selecting based on the rawExp value or the chipImfile value?
    psMetadataAddF64(queueArgs, PS_LIST_TAIL, "-bg",  0,
            "search by exposure background", NAN);
    psMetadataAddF64(queueArgs, PS_LIST_TAIL, "-bg_stdev",  0,
            "search by exposure background stdev", NAN);
    psMetadataAddF64(queueArgs, PS_LIST_TAIL, "-bg_mean_stdev",  0,
            "search by exposure 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);


    // -pendingimfile
    psMetadata *pendingimfileArgs = psMetadataAlloc();
    psMetadataAddStr(pendingimfileArgs, PS_LIST_TAIL, "-chip_id",  0,
            "search by chip ID", NULL);
    psMetadataAddStr(pendingimfileArgs, PS_LIST_TAIL, "-exp_tag",  0,
            "search by exposure 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);
    psMetadataAddStr(pendingimfileArgs, PS_LIST_TAIL, "-inst",  0,
            "search by camera of interest", NULL);
    psMetadataAddStr(pendingimfileArgs, PS_LIST_TAIL, "-filter",  0,
            "search by filter of interest", NULL); 
    psMetadataAddStr(pendingimfileArgs, PS_LIST_TAIL, "-uri",  0,
            "search by URL", NULL);
    psMetadataAddU64(pendingimfileArgs, PS_LIST_TAIL, "-limit",  0,
            "limit result set to N items", 0);
    psMetadataAddBool(pendingimfileArgs, PS_LIST_TAIL, "-simple",  0,
            "use the simple output format", false);
 
    // -addprocessedimfile
    psMetadata *addprocessedimfileArgs = psMetadataAlloc();
    psMetadataAddStr(addprocessedimfileArgs, PS_LIST_TAIL, "-chip_id",  0,
            "define chip ID (required)", NULL);
    psMetadataAddStr(addprocessedimfileArgs, PS_LIST_TAIL, "-class_id",  0,
            "define class ID (requied)", NULL);
    psMetadataAddStr(addprocessedimfileArgs, PS_LIST_TAIL, "-uri",  0,
            "define URL", NULL);
    psMetadataAddF32(addprocessedimfileArgs, PS_LIST_TAIL, "-bg",  0,
            "define exposure background", NAN);
    psMetadataAddF32(addprocessedimfileArgs, PS_LIST_TAIL, "-bg_stdev",  0,
            "define exposure background stdev", NAN);
    psMetadataAddF32(addprocessedimfileArgs, PS_LIST_TAIL, "-bg_mean_stdev",  0,
            "define exposure background mean stdev", NAN);

    psMetadataAddF32(addprocessedimfileArgs, PS_LIST_TAIL, "-bias",  0,
            "define bias", NAN);
    psMetadataAddF32(addprocessedimfileArgs, PS_LIST_TAIL, "-bias_stdev",  0,
            "define bias stdev", NAN);
    psMetadataAddF32(addprocessedimfileArgs, PS_LIST_TAIL, "-fringe_0",  0,
            "define fringe term 0", NAN);
    psMetadataAddF32(addprocessedimfileArgs, PS_LIST_TAIL, "-fringe_1",  0,
            "define fringe term 1", NAN);
    psMetadataAddF32(addprocessedimfileArgs, PS_LIST_TAIL, "-fringe_2",  0,
            "define fringe term 2", NAN);
    psMetadataAddF32(addprocessedimfileArgs, PS_LIST_TAIL, "-sigma_ra",  0,
            "define error in RA", NAN);
    psMetadataAddF32(addprocessedimfileArgs, PS_LIST_TAIL, "-sigma_dec",  0,
            "define error in DEC", NAN);
    psMetadataAddF32(addprocessedimfileArgs, PS_LIST_TAIL, "-ap_resid",  0,
            "define aperture residual", NAN);
    psMetadataAddF32(addprocessedimfileArgs, PS_LIST_TAIL, "-ap_resid_stdev",  0,
            "define aperture residual stdev", NAN);
    psMetadataAddF32(addprocessedimfileArgs, PS_LIST_TAIL, "-fwhm",  0,
            "define fwhm (arcsec)", NAN);
    psMetadataAddF32(addprocessedimfileArgs, PS_LIST_TAIL, "-fwhm_range",  0,
            "define fwhm range (min to max)", NAN);

    psMetadataAddS32(addprocessedimfileArgs, PS_LIST_TAIL, "-n_stars",  0,
            "define number of stars in image", 0);
    psMetadataAddS32(addprocessedimfileArgs, PS_LIST_TAIL, "-n_extended",  0,
            "define number of extended objects in image", 0);
    psMetadataAddS32(addprocessedimfileArgs, PS_LIST_TAIL, "-n_cr",  0,
            "define number of cosmic rays in image", 0);
    psMetadataAddS32(addprocessedimfileArgs, PS_LIST_TAIL, "-n_astrom",  0,
            "define number of astrometry stars used", 0);

    psMetadataAddStr(addprocessedimfileArgs, PS_LIST_TAIL, "-path_base",  0,
            "define base output location", NULL);
    psMetadataAddS16(addprocessedimfileArgs, PS_LIST_TAIL, "-code",  0,
            "set fault code", 0);

    // -processedimfile
    psMetadata *processedimfileArgs = psMetadataAlloc();
    psMetadataAddStr(processedimfileArgs, PS_LIST_TAIL, "-chip_id",  0,
            "define chip ID", NULL);
    psMetadataAddStr(processedimfileArgs, PS_LIST_TAIL, "-exp_tag",  0,
            "define exposure ID", NULL);
    psMetadataAddStr(processedimfileArgs, PS_LIST_TAIL, "-class",  0,
            "define class", NULL);
    psMetadataAddStr(processedimfileArgs, PS_LIST_TAIL, "-class_id",  0,
            "define class ID", NULL);
    psMetadataAddStr(processedimfileArgs, PS_LIST_TAIL, "-inst",  0,
            "define camera of interest", NULL);
    psMetadataAddStr(processedimfileArgs, PS_LIST_TAIL, "-filter",  0,
            "define filter of interest", NULL); 
    psMetadataAddStr(processedimfileArgs, PS_LIST_TAIL, "-uri",  0,
            "define URL", NULL);
    psMetadataAddU64(processedimfileArgs, PS_LIST_TAIL, "-limit",  0,
            "limit result set to N items", 0);
    psMetadataAddBool(processedimfileArgs, PS_LIST_TAIL, "-faulted",  0,
            "only return imfiles with a fault status set", false);
    psMetadataAddBool(processedimfileArgs, PS_LIST_TAIL, "-simple",  0,
            "use the simple output format", false);

    // -updateprocessedimfile
    psMetadata *updateprocessedimfileArgs = psMetadataAlloc();
    psMetadataAddStr(updateprocessedimfileArgs, PS_LIST_TAIL, "-chip_id",  0,
            "define chip ID", NULL);
    psMetadataAddStr(updateprocessedimfileArgs, PS_LIST_TAIL, "-exp_tag",  0,
            "search by exposure ID", NULL);
    psMetadataAddStr(updateprocessedimfileArgs, PS_LIST_TAIL, "-class",  0,
            "search by class", NULL);
    psMetadataAddStr(updateprocessedimfileArgs, PS_LIST_TAIL, "-class_id",  0,
            "search by class ID", NULL);
    psMetadataAddS16(updateprocessedimfileArgs, PS_LIST_TAIL, "-code",  0,
            "set fault code (required)", INT16_MAX);

    // -retryprocessedimfile
    psMetadata *retryprocessedimfileArgs = psMetadataAlloc();
    psMetadataAddStr(retryprocessedimfileArgs, PS_LIST_TAIL, "-chip_id",  0,
            "define chip ID (required)", NULL);
    psMetadataAddStr(retryprocessedimfileArgs, PS_LIST_TAIL, "-exp_tag",  0,
            "search by exposure ID", NULL);
    psMetadataAddStr(retryprocessedimfileArgs, PS_LIST_TAIL, "-class",  0,
            "search by class", NULL);
    psMetadataAddStr(retryprocessedimfileArgs, PS_LIST_TAIL, "-class_id",  0,
            "search by class ID", NULL);

    // -block
    psMetadata *blockArgs = psMetadataAlloc();
    psMetadataAddStr(blockArgs, PS_LIST_TAIL, "-label",  0,
            "name of a label to mask out (required)", 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 (required)", NULL);

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

    PXTOOL_ADD_MODE("-queue",               "", CHIPTOOL_MODE_QUEUE,          queueArgs);
    PXTOOL_ADD_MODE("-pendingimfile",       "", CHIPTOOL_MODE_PENDINGIMFILE,  pendingimfileArgs);
    PXTOOL_ADD_MODE("-addprocessedimfile",  "", CHIPTOOL_MODE_ADDPROCESSEDIMFILE,addprocessedimfileArgs);
    PXTOOL_ADD_MODE("-processedimfile",     "", CHIPTOOL_MODE_PROCESSEDIMFILE, processedimfileArgs);
    PXTOOL_ADD_MODE("-updateprocessedimfile", "", CHIPTOOL_MODE_UPDATEPROCESSEDIMFILE,    updateprocessedimfileArgs);
    PXTOOL_ADD_MODE("-retryprocessedimfile", "", CHIPTOOL_MODE_RETRYPROCESSEDIMFILE,    retryprocessedimfileArgs);
    PXTOOL_ADD_MODE("-block",               "",            CHIPTOOL_MODE_BLOCK,          blockArgs);
    PXTOOL_ADD_MODE("-masked",              "",      CHIPTOOL_MODE_MASKED,         maskedArgs);
    PXTOOL_ADD_MODE("-unblock",             "",  CHIPTOOL_MODE_UNBLOCK,        unblockArgs);

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



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

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

    addWhereStr(exp_tag);
    // 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(filter);
    addWhereStr(class);
    addWhereStr(class_id);

    /*
    // psMetadataConfig does not support times yet
    if (!psTimeIsZero(config->start) && !psTimeIsZero(config->stop)) {
        psMetadataAddTime (where, PS_LIST_TAIL, "TIME_START", 0, "<", config->stop);
        psMetadataAddTime (where, PS_LIST_TAIL, "TIME_STOP", 0, ">", config->start);
    }
    */

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

    return config;
}
