/*
 * 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 <math.h>
#include <stdint.h>

#include <psmodules.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();
    // XXX need to allow multiple chip_ids
    psMetadataAddStr(queueArgs, PS_LIST_TAIL, "-chip_id",  0,
            "search by chip_id", NULL);
    // XXX need to allow multiple exp_ids
    psMetadataAddStr(queueArgs, PS_LIST_TAIL, "-exp_id",  0,
            "search by exp_id", NULL);
    psMetadataAddStr(queueArgs, PS_LIST_TAIL, "-exp_name",  0,
            "search by exp_name", NULL);
    psMetadataAddStr(queueArgs, PS_LIST_TAIL, "-inst",  0,
            "search for camera", NULL);
    psMetadataAddStr(queueArgs, PS_LIST_TAIL, "-telescope",  0,
            "search for telescope", NULL);
    psMetadataAddTime(queueArgs, PS_LIST_TAIL, "-dateobs_begin", 0,
            "search for exposures by time (>=)", NULL);
    psMetadataAddTime(queueArgs, PS_LIST_TAIL, "-dateobs_end", 0,
            "search for exposures by time (<)", NULL);
    psMetadataAddStr(queueArgs, PS_LIST_TAIL, "-exp_tag",  0,
            "search by exp_tag", NULL);
    psMetadataAddStr(queueArgs, PS_LIST_TAIL, "-exp_type",  0,
            "search by exp_type", NULL);
    psMetadataAddStr(queueArgs, PS_LIST_TAIL, "-filelevel",  0,
            "search by filelevel", NULL);
    psMetadataAddStr(queueArgs, PS_LIST_TAIL, "-reduction",  0,
            "search by reduction class", NULL);
    psMetadataAddStr(queueArgs, PS_LIST_TAIL, "-filter",  0,
            "search for filter", NULL);
    psMetadataAddF32(queueArgs, PS_LIST_TAIL, "-airmass_min",  0,
            "define min airmass", NAN);
    psMetadataAddF32(queueArgs, PS_LIST_TAIL, "-airmass_max",  0,
            "define max airmass", NAN);
    psMetadataAddF64(queueArgs, PS_LIST_TAIL, "-ra_min",  0,
            "define min", NAN);
    psMetadataAddF64(queueArgs, PS_LIST_TAIL, "-ra_max",  0,
            "define max", NAN);
    psMetadataAddF64(queueArgs, PS_LIST_TAIL, "-decl_min",  0,
            "define min", NAN);
    psMetadataAddF64(queueArgs, PS_LIST_TAIL, "-decl_max",  0,
            "define max", NAN);
    psMetadataAddF32(queueArgs, PS_LIST_TAIL, "-exp_time_min",  0,
            "define min", NAN);
    psMetadataAddF32(queueArgs, PS_LIST_TAIL, "-exp_time_max",  0,
            "define max", NAN);
    psMetadataAddF32(queueArgs, PS_LIST_TAIL, "-sat_pixel_frac_min",  0,
            "define max fraction of saturated pixels", NAN);
    psMetadataAddF32(queueArgs, PS_LIST_TAIL, "-sat_pixel_frac_max",  0,
            "define min fraction of saturated pixels", NAN);
    psMetadataAddF64(queueArgs, PS_LIST_TAIL, "-bg_min",  0,
            "define max", NAN);
    psMetadataAddF64(queueArgs, PS_LIST_TAIL, "-bg_max",  0,
            "define max", NAN);
    psMetadataAddF64(queueArgs, PS_LIST_TAIL, "-bg_stdev_min",  0,
            "define max", NAN);
    psMetadataAddF64(queueArgs, PS_LIST_TAIL, "-bg_stdev_max",  0,
            "define max", NAN);
    psMetadataAddF64(queueArgs, PS_LIST_TAIL, "-bg_mean_stdev_min",  0,
            "define max", NAN);
    psMetadataAddF64(queueArgs, PS_LIST_TAIL, "-bg_mean_stdev_max",  0,
            "define max", NAN);
    psMetadataAddF64(queueArgs, PS_LIST_TAIL, "-alt_min",  0,
            "define min", NAN);
    psMetadataAddF64(queueArgs, PS_LIST_TAIL, "-alt_max",  0,
            "define max", NAN);
    psMetadataAddF64(queueArgs, PS_LIST_TAIL, "-az_min",  0,
            "define min", NAN);
    psMetadataAddF64(queueArgs, PS_LIST_TAIL, "-az_max",  0,
            "define max", NAN);
    psMetadataAddF64(queueArgs, PS_LIST_TAIL, "-ccd_temp_min",  0,
            "define min ccd tempature", NAN);
    psMetadataAddF64(queueArgs, PS_LIST_TAIL, "-ccd_temp_max",  0,
            "define max ccd tempature", NAN);
    psMetadataAddF64(queueArgs, PS_LIST_TAIL, "-posang_min",  0,
            "define min rotator position angle", NAN);
    psMetadataAddF64(queueArgs, PS_LIST_TAIL, "-posang_max",  0,
            "define max rotator position angle", NAN);
    psMetadataAddStr(queueArgs, PS_LIST_TAIL, "-object",  0,
            "search by exposure object", NULL);
    psMetadataAddF32(queueArgs, PS_LIST_TAIL, "-solang_min",  0,
            "define min solar angle", NAN);
    psMetadataAddF32(queueArgs, PS_LIST_TAIL, "-solang_max",  0,
            "define max solar angle", NAN);
    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_reduction",  0,
            "define reduction class", 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);
    psMetadataAddStr(queueArgs, PS_LIST_TAIL, "-set_tess_id",  0,
            "define tess ID", NULL);
    psMetadataAddStr(queueArgs, PS_LIST_TAIL, "-set_end_stage",  0,
            "define end stage", 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, "-uri", 0,
            "define URI (required)", NULL);
    psMetadataAddF64(addprocessedexpArgs, PS_LIST_TAIL, "-bg", 0,
            "define exposure background", NAN);
    psMetadataAddF64(addprocessedexpArgs, PS_LIST_TAIL, "-bg_stdev", 0,
            "define exposure background stdev", NAN);
    psMetadataAddF64(addprocessedexpArgs, PS_LIST_TAIL, "-bg_mean_stdev", 0,
            "define exposure background mean stdev", NAN);
    psMetadataAddF32(addprocessedexpArgs, PS_LIST_TAIL, "-bias",  0,
            "define bias", NAN);
    psMetadataAddF32(addprocessedexpArgs, PS_LIST_TAIL, "-bias_stdev",  0,
            "define bias stdev", NAN);
    psMetadataAddF32(addprocessedexpArgs, PS_LIST_TAIL, "-fringe_0",  0,
            "define fringe term 0", NAN);
    psMetadataAddF32(addprocessedexpArgs, PS_LIST_TAIL, "-fringe_1",  0,
            "define fringe term 1", NAN);
    psMetadataAddF32(addprocessedexpArgs, PS_LIST_TAIL, "-fringe_2",  0,
            "define fringe term 2", NAN);
    psMetadataAddF32(addprocessedexpArgs, PS_LIST_TAIL, "-sigma_ra", 0,
            "define exposure E ra", NAN);
    psMetadataAddF32(addprocessedexpArgs, PS_LIST_TAIL, "-sigma_dec", 0,
            "define exposure E dec", NAN);
    psMetadataAddF32(addprocessedexpArgs, PS_LIST_TAIL, "-ap_resid",  0,
            "define aperture residual", NAN);
    psMetadataAddF32(addprocessedexpArgs, PS_LIST_TAIL, "-ap_resid_stdev",  0,
            "define aperture residual stdev", NAN);
    psMetadataAddF32(addprocessedexpArgs, PS_LIST_TAIL, "-zp_mean", 0,
            "define zero point mean", NAN);
    psMetadataAddF32(addprocessedexpArgs, PS_LIST_TAIL, "-zp_stdev", 0,
            "define zero point stdev", NAN);
    psMetadataAddF32(addprocessedexpArgs, PS_LIST_TAIL, "-fwhm_major", 0,
            "define FWHM (major axis; arcsec)", NAN);
    psMetadataAddF32(addprocessedexpArgs, PS_LIST_TAIL, "-fwhm_minor", 0,
            "define FWHM (minor axis; arcsec)", NAN);
    psMetadataAddF32(addprocessedexpArgs, PS_LIST_TAIL, "-dtime_detrend", 0,
            "define elapsed detrend processing time (seconds)", NAN);
    psMetadataAddF32(addprocessedexpArgs, PS_LIST_TAIL, "-dtime_photom", 0,
            "define elapsed photometry processing time (seconds)", NAN);
    psMetadataAddF32(addprocessedexpArgs, PS_LIST_TAIL, "-dtime_astrom", 0,
            "define elapsed astrometry processing time (seconds)", NAN);
    psMetadataAddStr(addprocessedexpArgs, PS_LIST_TAIL, "-hostname", 0,
            "define hostname", NULL);
    psMetadataAddS32(addprocessedexpArgs, PS_LIST_TAIL, "-n_stars", 0,
            "define number of stars", 0);
    psMetadataAddS32(addprocessedexpArgs, PS_LIST_TAIL, "-n_extended", 0,
            "define number of extended objects", 0);
    psMetadataAddS32(addprocessedexpArgs, PS_LIST_TAIL, "-n_cr", 0,
            "define number of cosmic rays", 0);
    psMetadataAddS32(addprocessedexpArgs, PS_LIST_TAIL, "-n_astrom", 0,
            "define number of astrometry reference objects", 0);
    psMetadataAddStr(addprocessedexpArgs, PS_LIST_TAIL, "-path_base", 0,
            "define base output location", NULL);
    psMetadataAddS16(addprocessedexpArgs, PS_LIST_TAIL, "-code",  0,
            "set fault code", 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);

    // -revertprocessedexp
    psMetadata *revertprocessedexpArgs = psMetadataAlloc();
    psMetadataAddStr(revertprocessedexpArgs, PS_LIST_TAIL, "-cam_id", 0,
            "search by camtool ID (required)", NULL);
    psMetadataAddStr(revertprocessedexpArgs, PS_LIST_TAIL, "-chip_id", 0,
            "search by chiptool ID", NULL);
    psMetadataAddS16(revertprocessedexpArgs, PS_LIST_TAIL, "-code",  0,
            "search by fault code", 0);

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

    // -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();

    PXOPT_ADD_MODE("-queue",               "", CAMTOOL_MODE_QUEUE,         queueArgs);
    PXOPT_ADD_MODE("-pendingexp",          "", CAMTOOL_MODE_PENDINGEXP,    pendingexpArgs);
    PXOPT_ADD_MODE("-pendingimfile",       "", CAMTOOL_MODE_PENDINGIMFILE, pendingimfileArgs);
    PXOPT_ADD_MODE("-addprocessedexp",     "", CAMTOOL_MODE_ADDPROCESSEDEXP, addprocessedexpArgs);
    PXOPT_ADD_MODE("-processedexp",        "", CAMTOOL_MODE_PROCESSEDEXP,  processedexpArgs);
    PXOPT_ADD_MODE("-revertprocessedexp",  "", CAMTOOL_MODE_REVERTPROCESSEDEXP,  revertprocessedexpArgs);
    PXOPT_ADD_MODE("-updateprocessedexp",  "", CAMTOOL_MODE_UPDATEPROCESSEDEXP,updateprocessedexpArgs);
    PXOPT_ADD_MODE("-block",               "", CAMTOOL_MODE_BLOCK,         blockArgs);
    PXOPT_ADD_MODE("-masked",              "", CAMTOOL_MODE_MASKED,        maskedArgs);
    PXOPT_ADD_MODE("-unblock",             "", CAMTOOL_MODE_UNBLOCK,       unblockArgs);

    if (!pxGetOptions(stderr, argc, argv, config, modes, argSets)) {
        psError(PS_ERR_UNKNOWN, false, "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, "-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_id);
    addWhereStr(filter);

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

    return config;
}
