/*
 * flatcorrConfig.c
 *
 * Copyright (C) 2006-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 "flatcorr.h"

pxConfig *flatcorrConfig(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 *now = psTimeGetNow(PS_TIME_TAI);

    // -newrun
    psMetadata *newrunArgs = psMetadataAlloc();
    // XXX need to allow multiple exp_ids
    psMetadataAddStr(newrunArgs, PS_LIST_TAIL, "-exp_id",  0,
            "search by exp_id", NULL);
    psMetadataAddStr(newrunArgs, PS_LIST_TAIL, "-exp_name",  0,
            "search by exp_name", NULL);
    psMetadataAddStr(newrunArgs, PS_LIST_TAIL, "-inst",  0,
            "search for camera", NULL); 
    psMetadataAddStr(newrunArgs, PS_LIST_TAIL, "-telescope",  0,
            "search for telescope", NULL);
    psMetadataAddTime(newrunArgs, PS_LIST_TAIL, "-dateobs_begin", 0,   
            "search for exposures by time (>=)", NULL);
    psMetadataAddTime(newrunArgs, PS_LIST_TAIL, "-dateobs_end", 0,
            "search for exposures by time (<)", NULL);
    psMetadataAddStr(newrunArgs, PS_LIST_TAIL, "-exp_tag",  0,
            "search by exp_tag", NULL);
    psMetadataAddStr(newrunArgs, PS_LIST_TAIL, "-exp_type",  0,
            "search by exp_type", "object");
    psMetadataAddStr(newrunArgs, PS_LIST_TAIL, "-filelevel",  0,
            "search by filelevel", NULL);
    psMetadataAddStr(newrunArgs, PS_LIST_TAIL, "-reduction",  0,
            "search by reduction class", NULL);
    psMetadataAddStr(newrunArgs, PS_LIST_TAIL, "-filter",  0,
            "search for filter", NULL); 
    psMetadataAddF32(newrunArgs, PS_LIST_TAIL, "-airmass_min",  0,
            "define min airmass", NAN);
    psMetadataAddF32(newrunArgs, PS_LIST_TAIL, "-airmass_max",  0,
            "define max airmass", NAN); 
    psMetadataAddF64(newrunArgs, PS_LIST_TAIL, "-ra_min",  0,
            "define min", NAN);
    psMetadataAddF64(newrunArgs, PS_LIST_TAIL, "-ra_max",  0,
            "define max", NAN); 
    psMetadataAddF64(newrunArgs, PS_LIST_TAIL, "-decl_min",  0,
            "define min", NAN);
    psMetadataAddF64(newrunArgs, PS_LIST_TAIL, "-decl_max",  0,
            "define max", NAN); 
    psMetadataAddF32(newrunArgs, PS_LIST_TAIL, "-exp_time_min",  0,
            "define min", NAN);
    psMetadataAddF32(newrunArgs, PS_LIST_TAIL, "-exp_time_max",  0,
            "define max", NAN); 
    psMetadataAddF32(newrunArgs, PS_LIST_TAIL, "-sat_pixel_frac_min",  0,
            "define max fraction of saturated pixels", NAN);
    psMetadataAddF32(newrunArgs, PS_LIST_TAIL, "-sat_pixel_frac_max",  0,
            "define min fraction of saturated pixels", NAN);
    psMetadataAddF64(newrunArgs, PS_LIST_TAIL, "-bg_min",  0,
            "define max", NAN);
    psMetadataAddF64(newrunArgs, PS_LIST_TAIL, "-bg_max",  0,
            "define max", NAN);
    psMetadataAddF64(newrunArgs, PS_LIST_TAIL, "-bg_stdev_min",  0,
            "define max", NAN);
    psMetadataAddF64(newrunArgs, PS_LIST_TAIL, "-bg_stdev_max",  0,
            "define max", NAN);
    psMetadataAddF64(newrunArgs, PS_LIST_TAIL, "-bg_mean_stdev_min",  0,
            "define max", NAN);
    psMetadataAddF64(newrunArgs, PS_LIST_TAIL, "-bg_mean_stdev_max",  0,
            "define max", NAN);
    psMetadataAddF64(newrunArgs, PS_LIST_TAIL, "-alt_min",  0,
            "define min", NAN);
    psMetadataAddF64(newrunArgs, PS_LIST_TAIL, "-alt_max",  0,
            "define max", NAN); 
    psMetadataAddF64(newrunArgs, PS_LIST_TAIL, "-az_min",  0,
            "define min", NAN);
    psMetadataAddF64(newrunArgs, PS_LIST_TAIL, "-az_max",  0,
            "define max", NAN);
    psMetadataAddF64(newrunArgs, PS_LIST_TAIL, "-ccd_temp_min",  0,   
            "define min ccd tempature", NAN);
    psMetadataAddF64(newrunArgs, PS_LIST_TAIL, "-ccd_temp_max",  0,
            "define max ccd tempature", NAN);
    psMetadataAddF64(newrunArgs, PS_LIST_TAIL, "-posang_min",  0,
            "define min rotator position angle", NAN);
    psMetadataAddF64(newrunArgs, PS_LIST_TAIL, "-posang_max",  0,
            "define max rotator position angle", NAN);
    psMetadataAddStr(newrunArgs, PS_LIST_TAIL, "-object",  0,
            "search by exposure object", NULL);
    psMetadataAddF32(newrunArgs, PS_LIST_TAIL, "-solang_min",  0,
            "define min solar angle", NAN);
    psMetadataAddF32(newrunArgs, PS_LIST_TAIL, "-solang_max",  0,
            "define max solar angle", NAN);
    psMetadataAddStr(newrunArgs, PS_LIST_TAIL, "-set_workdir",  0,
            "define workdir", NULL);
    psMetadataAddStr(newrunArgs, PS_LIST_TAIL, "-set_label",  0,
            "define label", NULL);
    psMetadataAddStr(newrunArgs, PS_LIST_TAIL, "-set_reduction",  0,
            "define reduction class", NULL);
    psMetadataAddStr(newrunArgs, PS_LIST_TAIL, "-set_expgroup",  0,
            "define exposure group", NULL);
    psMetadataAddStr(newrunArgs, PS_LIST_TAIL, "-set_dvodb",  0,
            "define DVO db", NULL);
    psMetadataAddStr(newrunArgs, PS_LIST_TAIL, "-set_filter",  0,
            "define filter", NULL);
    psMetadataAddStr(newrunArgs, PS_LIST_TAIL, "-set_tess_id",  0,
            "define tessalation", NULL);
    psMetadataAddStr(newrunArgs, PS_LIST_TAIL, "-set_end_stage",  0,
            "define processing end stage", NULL);
    psMetadataAddStr(newrunArgs, PS_LIST_TAIL, "-set_region",  0,
            "define region", NULL);

    psMetadataAddBool(newrunArgs, PS_LIST_TAIL, "-pretend",  0,
            "print the exposures that would be included in the detrend run and exit", false);
    psMetadataAddBool(newrunArgs, PS_LIST_TAIL, "-simple", 0,
            "use the simple output format", false);

    // -addexp
    psMetadata *addexpArgs = psMetadataAlloc();
    psMetadataAddStr(addexpArgs, PS_LIST_TAIL, "-corr_id", 0,
            "define Flat Correction ID (required)", NULL);
    psMetadataAddStr(addexpArgs, PS_LIST_TAIL, "-chip_id", 0,
            "define Chip ID (required)", NULL);

    // -pending
    psMetadata *pendingArgs = psMetadataAlloc();
    psMetadataAddU64(pendingArgs, PS_LIST_TAIL, "-limit",  0,
            "limit result set to N items", 0);
    psMetadataAddBool(pendingArgs, PS_LIST_TAIL, "-simple", 0,
            "use the simple output format", false);

    // -flatcorrimfile
    psMetadata *flatcorrimfileArgs = psMetadataAlloc();
    psMetadataAddStr(flatcorrimfileArgs, PS_LIST_TAIL, "-corr_id",  0,
            "search by flat correction ID (required)", NULL);
    psMetadataAddU64(flatcorrimfileArgs, PS_LIST_TAIL, "-limit",  0,
            "limit result set to N items", 0);
    psMetadataAddBool(flatcorrimfileArgs, PS_LIST_TAIL, "-simple", 0,
            "use the simple output format", false);

    // -done
    psMetadata *doneArgs = psMetadataAlloc();
    psMetadataAddStr(doneArgs, PS_LIST_TAIL, "-corr_id",  0,
            "define correction id (required)", NULL);
    psMetadataAddStr(doneArgs, PS_LIST_TAIL, "-stats",  0,
            "define stats (required)", NULL);

    // -updaterun
    psMetadata *updaterunArgs = psMetadataAlloc();
    psMetadataAddStr(updaterunArgs, PS_LIST_TAIL, "-corr_id",  0,
            "define correction id (required)", NULL);
    psMetadataAddStr(updaterunArgs, PS_LIST_TAIL, "-state", 0,
            "set state (required)", NULL);

    psFree(now);

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

    PXOPT_ADD_MODE("-newrun",  "start a new flat correction run",
        FLATCORR_MODE_NEWRUN,       newrunArgs);
    PXOPT_ADD_MODE("-addexp",  "add an exp to a flat correction run",
        FLATCORR_MODE_ADDEXP,       addexpArgs);
    PXOPT_ADD_MODE("-pending", "show flat correction runs needing to be processed",
        FLATCORR_MODE_PENDING,      pendingArgs);
    PXOPT_ADD_MODE("-flatcorrimfile", "list all the imfiles in a flat correction run",
        FLATCORR_MODE_FLATCORRIMFILE, flatcorrimfileArgs);
    PXOPT_ADD_MODE("-done",  "change a flat calibration run's state",
        FLATCORR_MODE_DONE,         doneArgs);
    PXOPT_ADD_MODE("-updaterun",  "change a flat calibration run's state",
        FLATCORR_MODE_UPDATERUN,   updaterunArgs);

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