/*
 * pstamptool.c
 *
 * Copyright (C) 2008  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 <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <inttypes.h>

#include "pxtools.h"
#include "pxdata.h"
#include "pstamptool.h"

static bool adddatastoreMode(pxConfig *config);
static bool datastoreMode(pxConfig *config);
static bool moddatastoreMode(pxConfig *config);
static bool addReqMode(pxConfig *config);
static bool completedReqMode(pxConfig *config);
static bool listReqMode(pxConfig *config);
static bool pendingReqMode(pxConfig *config);
static bool processedReqMode(pxConfig *config);
static bool addJobMode(pxConfig *config);
static bool listJobMode(pxConfig *config);
static bool pendingJobMode(pxConfig *config);
static bool processedJobMode(pxConfig *config);

# define MODECASE(caseName, func) \
    case caseName: \
    if (!func(config)) { \
                goto FAIL; \
            } \
    break;


int main(int argc, char **argv)
{
    psLibInit(NULL);

    pxConfig *config = pstamptoolConfig(NULL, argc, argv);
    if (!config) {
        psError(PXTOOLS_ERR_CONFIG, false, "failed to configure");
        goto FAIL;
    }

    switch (config->mode) {
        MODECASE(PSTAMPTOOL_MODE_ADDDATASTORE, adddatastoreMode);
        MODECASE(PSTAMPTOOL_MODE_DATASTORE, datastoreMode);
        MODECASE(PSTAMPTOOL_MODE_MODDATASTORE, moddatastoreMode);
        MODECASE(PSTAMPTOOL_MODE_ADDREQ, addReqMode);
        MODECASE(PSTAMPTOOL_MODE_COMPLETEDREQ, completedReqMode);
        MODECASE(PSTAMPTOOL_MODE_LISTREQ, listReqMode);
        MODECASE(PSTAMPTOOL_MODE_PENDINGREQ, pendingReqMode);
        MODECASE(PSTAMPTOOL_MODE_PROCESSEDREQ, processedReqMode);
        MODECASE(PSTAMPTOOL_MODE_ADDJOB, addJobMode);
        MODECASE(PSTAMPTOOL_MODE_LISTJOB, listJobMode);
        MODECASE(PSTAMPTOOL_MODE_PENDINGJOB, pendingJobMode);
        MODECASE(PSTAMPTOOL_MODE_PROCESSEDJOB, processedJobMode);
        default:
            psAbort("invalid option (this should not happen)");
    }

    psFree(config);
    pmConfigDone();
    psLibFinalize();

    exit(EXIT_SUCCESS);

FAIL:
    psErrorStackPrint(stderr, "\n");
    int exit_status = pxerrorGetExitStatus();

    psFree(config);
    pmConfigDone();
    psLibFinalize();

    exit(exit_status);
}

static bool adddatastoreMode(pxConfig *config)
{
    PS_ASSERT_PTR_NON_NULL(config, false);

    PXOPT_LOOKUP_STR(uri,         config->args, "-uri",           true, false);
    PXOPT_LOOKUP_STR(outProduct,  config->args, "-out_product",   true, false);
    PXOPT_LOOKUP_STR(lastFileset, config->args, "-last_fileset", false, false);
    PXOPT_LOOKUP_STR(state,       config->args, "-state",         false, false);

    if (!pstampDataStoreInsert(config->dbh,
            0,
            state,
            lastFileset,
            outProduct,
            uri
        )) {
        psError(PS_ERR_UNKNOWN, false, "database error");
        return false;
    }

    return true;
}

static bool datastoreMode(pxConfig *config)
{
    PS_ASSERT_PTR_NON_NULL(config, false);

    psMetadata *where = psMetadataAlloc();
    PXOPT_COPY_STR(config->args, where, "-ds_id", "ds_id", "==");

    PXOPT_LOOKUP_BOOL(simple, config->args, "-simple", false);

    psString query = pxDataGet("pstamptool_datastore.sql");
    if (!query) {
        psError(PXTOOLS_ERR_DATA, false, "failed to retreive SQL statement");
        return false;
    }

    if (psListLength(where->list)) {
        psString whereClause = psDBGenerateWhereSQL(where, NULL);
        psStringAppend(&query, " %s", whereClause);
        psFree(whereClause);
    }
    psFree(where);

    if (!p_psDBRunQuery(config->dbh, query)) {
        psError(PS_ERR_UNKNOWN, false, "database error");
        return false;
    }

    psArray *output = p_psDBFetchResult(config->dbh);
    if (!output) {
        psError(PS_ERR_UNKNOWN, false, "database error");
        return false;
    }
    if (!psArrayLength(output)) {
        psTrace("pstamptool", PS_LOG_INFO, "no rows found");
        psFree(output);
        return true;
    }

    // negative simple so the default is true
    if (!ippdbPrintMetadatas(stdout, output, "pstampDataStore", !simple)) {
        psError(PS_ERR_UNKNOWN, false, "failed to print array");
        psFree(output);
        return false;
    }

    psFree(output);

    return true;
}
static bool moddatastoreMode(pxConfig *config)
{
    PS_ASSERT_PTR_NON_NULL(config, false);

    PXOPT_LOOKUP_STR(ds_id,       config->args, "-ds_id",         true, false);
    PXOPT_LOOKUP_STR(lastFileset, config->args, "-last_fileset",  false, false);
    PXOPT_LOOKUP_STR(state,       config->args, "-state",         false, false);

    if (!state && !lastFileset) {
        psError(PS_ERR_UNKNOWN, true, "at least one of -last_fileset or -state is required");
        return false;
    }

    char *query = psStringCopy ("UPDATE pstampDataStore SET");
    bool needComma = false;
    
    if (lastFileset) {
        psStringAppend(&query, " lastFileset = '%s'", lastFileset);
        needComma = true;
    }

    if (state) {
        psStringAppend(&query, "%s state = '%s'", needComma ? "," : " ", state);
        needComma = true; // be ready in case we add another field
    }
                
    psStringAppend(&query, " WHERE ds_id = '%s'", ds_id);

    if (!p_psDBRunQuery(config->dbh, query)) {
        psError(PS_ERR_UNKNOWN, false, "database error");
        psFree(query);
        return false;
    }

    psU64 affected = psDBAffectedRows(config->dbh);
    if (affected != 1) {
        psError(PS_ERR_UNKNOWN, false, "should have affected one row but %" 
                                        PRIu64 " rows were modified", affected);
        return false;
    }

    return true;
}

#define  MAGIC_STR  "$REQ_ID"

// Replace $REQ_ID with the value of the request id if present in the outFileset
// XXX EAM : rewrite this using psStringSubstitute:
// word = psStringAppend (NULL, "%" PRId64, req_id;
// converted = psStringSubstitute (outFileset, word, MAGIC_STR); 

static bool
updateFilesetID(pxConfig *config, psS64 req_id, psString outFileset)
{
    char *magic;

    magic = strcasestr(outFileset, MAGIC_STR);
    if (magic == NULL) {
        return true;
    }

    // find part of the string after the magic
    char *after = magic + strlen(MAGIC_STR);

    if (*after == 0) {
        after = NULL;
    }

    psString converted = NULL;
    if (magic > outFileset) {
        int len = magic - outFileset;
        converted = psStringAlloc(len + 1);
        strncpy(converted, outFileset, len);
        converted[len] = 0;
    }

    psStringAppend(&converted, "%" PRId64, req_id);
    if (after) {
        psStringAppend(&converted, after);
    }

    if (!p_psDBRunQuery(config->dbh, "UPDATE pstampRequest set outFileset = '%s' WHERE req_id = %" PRId64,
            converted, req_id)) {
        psError(PS_ERR_UNKNOWN, false, "database error");
        return false;
    }

    return true;
}

static bool addReqMode(pxConfig *config)
{
    PS_ASSERT_PTR_NON_NULL(config, false);

    PXOPT_LOOKUP_STR(uri,         config->args, "-uri",           true, false);
    PXOPT_LOOKUP_STR(outFileset,  config->args, "-out_fileset",   true, false);
    PXOPT_LOOKUP_STR(ds_id,       config->args, "-ds_id",         false, false);

    char *query ="INSERT INTO pstampRequest"
                 " (state, uri, ds_id, outFileset, resultsFile)"
                 " VALUES( 'new', '%s', %s, '%s', 0)";

    if (!p_psDBRunQuery(config->dbh, query, uri, ds_id, outFileset)) {
        psError(PS_ERR_UNKNOWN, false, "database error");
        return false;
    }

    psU64 affected = psDBAffectedRows(config->dbh);
    if (affected != 1) {
        psError(PS_ERR_UNKNOWN, false, 
            "should have affected one row but %" PRIu64 " rows were modified",
            affected);
        return false;
    }

    psS64 req_id = psDBLastInsertID(config->dbh);
    if (!updateFilesetID(config, req_id, outFileset)) {
        psError(PS_ERR_UNKNOWN, false, "failed to update fileset id\n");
        return false;
    }

    printf("%" PRId64 "\n", req_id);

    return true;
}

static bool pendingReqMode(pxConfig *config)
{
    PS_ASSERT_PTR_NON_NULL(config, false);

    psMetadata *where = psMetadataAlloc();
    PXOPT_COPY_STR(config->args, where, "-ds_id", "ds_id", "==");

    PXOPT_LOOKUP_U64(limit, config->args, "-limit", false, false);
    PXOPT_LOOKUP_BOOL(simple, config->args, "-simple", false);

    psString query = pxDataGet("pstamptool_pendingreq.sql");
    if (!query) {
        psError(PXTOOLS_ERR_DATA, false, "failed to retreive SQL statement");
        return false;
    }

    if (psListLength(where->list)) {
        psString whereClause = psDBGenerateWhereConditionSQL(where, "pstampRequest");
        psStringAppend(&query, " AND %s", whereClause);
        psFree(whereClause);
    }
    psFree(where);

    // treat limit == 0 as "no limit"
    if (limit) {
        psString limitString = psDBGenerateLimitSQL(limit);
        psStringAppend(&query, " %s", limitString);
        psFree(limitString);
    }

    if (!p_psDBRunQuery(config->dbh, query)) {
        psError(PS_ERR_UNKNOWN, false, "database error");
        psFree(query);
        return false;
    }
    psFree(query);

    psArray *output = p_psDBFetchResult(config->dbh);
    if (!output) {
        psError(PS_ERR_UNKNOWN, false, "database error");
        return false;
    }
    if (!psArrayLength(output)) {
        psTrace("pstamptool", PS_LOG_INFO, "no rows found");
        psFree(output);
        return true;
    }

    // negative simple so the default is true
    if (!ippdbPrintMetadatas(stdout, output, "pstampRequest", !simple)) {
        psError(PS_ERR_UNKNOWN, false, "failed to print array");
        psFree(output);
        return false;
    }

    psFree(output);

    return true;
}

static bool listReqMode(pxConfig *config)
{
    PS_ASSERT_PTR_NON_NULL(config, false);

    PXOPT_LOOKUP_STR(req_id,  config->args, "-req_id", true, false);
    PXOPT_LOOKUP_U64(limit,   config->args, "-limit",  false, false);
    PXOPT_LOOKUP_BOOL(simple, config->args, "-simple", false);

    psString query = NULL;
    psStringAppend(&query, "SELECT"
		   " *"
		   " FROM pstampRequest"
		   " WHERE req_id = %s", req_id);

    // treat limit == 0 as "no limit"
    if (limit) {
        psString limitString = psDBGenerateLimitSQL(limit);
        psStringAppend(&query, " %s", limitString);
        psFree(limitString);
    }

    if (!p_psDBRunQuery(config->dbh, query)) {
        psError(PS_ERR_UNKNOWN, false, "database error");
        psFree(query);
        return false;
    }
    psFree(query);

    psArray *output = p_psDBFetchResult(config->dbh);
    if (!output) {
        psError(PS_ERR_UNKNOWN, false, "database error");
        return false;
    }
    if (!psArrayLength(output)) {
        psTrace("pstamptool", PS_LOG_INFO, "no rows found");
        psFree(output);
        return true;
    }

    // negative simple so the default is true
    if (!ippdbPrintMetadatas(stdout, output, "pstampRequest", !simple)) {
        psError(PS_ERR_UNKNOWN, false, "failed to print array");
        psFree(output);
        return false;
    }

    psFree(output);

    return true;
}

static bool completedReqMode(pxConfig *config)
{
    PS_ASSERT_PTR_NON_NULL(config, false);

    PXOPT_LOOKUP_U64(limit, config->args, "-limit", false, false);
    PXOPT_LOOKUP_BOOL(simple, config->args, "-simple", false);

    psString query = 
        "SELECT * FROM pstampRequest WHERE state = 'run' AND "
            "(SELECT count(*) FROM pstampJob WHERE pstampJob.req_id = pstampRequest.req_id "
            " AND pstampJob.state != 'stop') = 0" ;

    // treat limit == 0 as "no limit"
    if (limit) {
        psString limitString = psDBGenerateLimitSQL(limit);
        psStringAppend(&query, " %s", limitString);
        psFree(limitString);
    }

    if (!p_psDBRunQuery(config->dbh, query)) {
        psError(PS_ERR_UNKNOWN, false, "database error");
        psFree(query);
        return false;
    }

    psArray *output = p_psDBFetchResult(config->dbh);
    if (!output) {
        psError(PS_ERR_UNKNOWN, false, "database error");
        return false;
    }

    if (!psArrayLength(output)) {
        psTrace("pstamptool", PS_LOG_INFO, "no rows found");
        psFree(output);
        return true;
    }

    // negative simple so the default is true
    if (!ippdbPrintMetadatas(stdout, output, "pstampRequest", !simple)) {
        psError(PS_ERR_UNKNOWN, false, "failed to print array");
        psFree(output);
        return false;
    }

    psFree(output);

    return true;
}

static bool processedReqMode(pxConfig *config)
{
    PS_ASSERT_PTR_NON_NULL(config, false);

    PXOPT_LOOKUP_STR(req_id, config->args, "-req_id", true, false);
    PXOPT_LOOKUP_STR(state,  config->args, "-state",  true, false);

    // XXX: check state for a legal value

    char *query ="UPDATE pstampRequest"
                 " SET state = '%s'"
                 " WHERE req_id = '%s'";

    if (!p_psDBRunQuery(config->dbh, query, state, req_id)) {
        psError(PS_ERR_UNKNOWN, false, "database error");
        psFree(query);
        return false;
    }

    psU64 affected = psDBAffectedRows(config->dbh);
    if (affected != 1) {
        psError(PS_ERR_UNKNOWN, false, "should have affected one row but %" 
                                        PRIu64 " rows were modified", affected);
        return false;
    }

    return true;
}

static bool addJobMode(pxConfig *config)
{
    bool    stampJob = false;
    char   *query = NULL;

    PS_ASSERT_PTR_NON_NULL(config, false);

    PXOPT_LOOKUP_STR(uri,         config->args, "-uri",        true, false);
    PXOPT_LOOKUP_STR(req_id,      config->args, "-req_id",     true, false);
    PXOPT_LOOKUP_STR(job_type,    config->args, "-job_type",   false, false);
    PXOPT_LOOKUP_STR(outputBase,  config->args, "-outputBase", true,  false);
    PXOPT_LOOKUP_STR(argString,   config->args, "-args",       true,  false);
    PXOPT_LOOKUP_STR(stateString, config->args, "-state",      false, false);
    PXOPT_LOOKUP_STR(result,      config->args, "-result",     false, false);

    if (!strcmp(job_type, "get_image") || !strcmp(job_type, "detect_query")) {
	stampJob = false;
    } else if (!strcmp(job_type, "stamp")) {
	stampJob = true;
    } else {
	psError(PS_ERR_UNKNOWN, false, "unknown value for -job_type: %s", job_type);
	return false;
    }
    
    if (stampJob) {
	query = pxDataGet("pstamptool_addjob_stampjob.sql");
    } else {
	query = pxDataGet("pstamptool_addjob_otherjob.sql");
    }
    if (!query) {
        psError(PXTOOLS_ERR_DATA, false, "failed to retreive SQL statement");
        return false;
    }

    if (!p_psDBRunQuery(config->dbh, query, req_id, stateString, job_type, uri, outputBase, result, argString)) {
        psError(PS_ERR_UNKNOWN, false, "database error");
        return false;
    }

    psU64 affected = psDBAffectedRows(config->dbh);
    if (affected != 1) {
        psError(PS_ERR_UNKNOWN, false, 
            "should have affected one row but %" PRIu64 " rows were modified",
            affected);
        return false;
    }

    psS64 job_id = psDBLastInsertID(config->dbh);
    printf("%" PRId64 "\n", job_id);

    return true;
}

static bool listJobMode(pxConfig *config)
{
    PS_ASSERT_PTR_NON_NULL(config, false);

    PXOPT_LOOKUP_STR(req_id, config->args, "-req_id", false, false);
    PXOPT_LOOKUP_STR(job_id, config->args, "-job_id", false, false);

    PXOPT_LOOKUP_U64(limit, config->args, "-limit", false, false);
    PXOPT_LOOKUP_BOOL(simple, config->args, "-simple", false);

    psString query = NULL;

    if (!req_id && !job_id) {
        fprintf(stderr, "either req_id or job_id must be specified\n");
        exit (1);
    }

    if (req_id) {
        psStringAppend(&query,
                "SELECT"
                " *"
                " FROM pstampJob"
                " WHERE req_id = %s", req_id
            );
    } else {
        psStringAppend(&query,
                "SELECT"
                " *"
                " FROM pstampJob"
                " WHERE job_id = %s", job_id
            );
    } 

    // treat limit == 0 as "no limit"
    if (limit) {
        psString limitString = psDBGenerateLimitSQL(limit);
        psStringAppend(&query, " %s", limitString);
        psFree(limitString);
    }

    if (!p_psDBRunQuery(config->dbh, query)) {
        psError(PS_ERR_UNKNOWN, false, "database error");
        psFree(query);
        return false;
    }
    psFree(query);

    psArray *output = p_psDBFetchResult(config->dbh);
    if (!output) {
        psError(PS_ERR_UNKNOWN, false, "database error");
        return false;
    }
    if (!psArrayLength(output)) {
        psTrace("pstamptool", PS_LOG_INFO, "no rows found");
        psFree(output);
        return true;
    }

    // negative simple so the default is true
    if (!ippdbPrintMetadatas(stdout, output, "pstampJob", !simple)) {
        psError(PS_ERR_UNKNOWN, false, "failed to print array");
        psFree(output);
        return false;
    }

    psFree(output);

    return true;
}

static bool pendingJobMode(pxConfig *config)
{
    PS_ASSERT_PTR_NON_NULL(config, false);

    psMetadata *where = psMetadataAlloc();
    PXOPT_COPY_S64(config->args, where, "-cam_id", "cam_id", "==");

    PXOPT_LOOKUP_U64(limit, config->args, "-limit", false, false);
    PXOPT_LOOKUP_BOOL(simple, config->args, "-simple", false);

    psString query = pxDataGet("pstamptool_pendingjob.sql");
    if (!query) {
        psError(PXTOOLS_ERR_DATA, false, "failed to retreive SQL statement");
        return false;
    }

    // use psDBGenerateWhereSQL because the SQL yields an intermediate table
    if (psListLength(where->list)) {
        psString whereClause = psDBGenerateWhereConditionSQL(where, "pstampJob");
        psStringAppend(&query, " AND %s", whereClause);
        psFree(whereClause);
    }
    psFree(where);

    // treat limit == 0 as "no limit"
    if (limit) {
        psString limitString = psDBGenerateLimitSQL(limit);
        psStringAppend(&query, " %s", limitString);
        psFree(limitString);
    }

    if (!p_psDBRunQuery(config->dbh, query)) {
        psError(PS_ERR_UNKNOWN, false, "database error");
        psFree(query);
        return false;
    }
    psFree(query);

    psArray *output = p_psDBFetchResult(config->dbh);
    if (!output) {
        psError(PS_ERR_UNKNOWN, false, "database error");
        return false;
    }
    if (!psArrayLength(output)) {
        psTrace("pstamptool", PS_LOG_INFO, "no rows found");
        psFree(output);
        return true;
    }

    // negative simple so the default is true
    if (!ippdbPrintMetadatas(stdout, output, "pstampJob", !simple)) {
        psError(PS_ERR_UNKNOWN, false, "failed to print array");
        psFree(output);
        return false;
    }

    psFree(output);

    return true;
}

static bool processedJobMode(pxConfig *config)
{
    bool    status;
    char *query = NULL;

    PS_ASSERT_PTR_NON_NULL(config, false);

    PXOPT_LOOKUP_STR(job_id,    config->args, "-job_id", true, false);
    PXOPT_LOOKUP_STR(state,     config->args, "-state",  true, false);
    PXOPT_LOOKUP_STR(jobResult, config->args, "-result", false, false);
    // XXX: check state for a legal value

    if (jobResult) {
	query = psStringCopy ("UPDATE pstampJob"
			      " SET state = '%s', result = '%s'"
			      " WHERE job_id = '%s'");
	status = p_psDBRunQuery(config->dbh, query, state, jobResult, job_id);
    } else {
	query = psStringCopy ("UPDATE pstampJob"
			      " SET state = '%s'"
			      " WHERE job_id = '%s'");
	status = p_psDBRunQuery(config->dbh, query, state, job_id);
    }

    if (!status) {
        psError(PS_ERR_UNKNOWN, false, "database error");
        psFree(query);
        return false;
    }

    psU64 affected = psDBAffectedRows(config->dbh);
    if (affected != 1) {
        psError(PS_ERR_UNKNOWN, false, "should have affected one row but %" 
                                        PRIu64 " rows were modified", affected);
        return false;
    }

    return true;
}
