/*
 * pxchip.c
 *
 * Copyright (C) 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 <stdlib.h>
#include <ippdb.h>
#include <string.h>

#include "pxtools.h"
#include "pxchip.h"

bool pxchipRunSetState(pxConfig *config, psS64 chip_id, const char *state)
{
    PS_ASSERT_PTR_NON_NULL(state, false);

    // check that state is a valid string value
    if (!(
            (strncmp(state, "run", 4) == 0)
            || (strncmp(state, "stop", 5) == 0)
            || (strncmp(state, "reg", 4) == 0)
        )
    ) {
        psError(PS_ERR_UNKNOWN, false,
                "invalid chipRun state: %s", state);
        return false;
    }

    char *query = "UPDATE chipRun SET state = '%s' WHERE chip_id = %" PRId64;
    if (!p_psDBRunQuery(config->dbh, query, state, chip_id)) {
        psError(PS_ERR_UNKNOWN, false,
                "failed to change state for chip_id %" PRId64, chip_id);
        return false;
    }

    return true;
}


bool pxchipQueueByExpTag(pxConfig *config,
                         psS64 exp_id,
                         psString workdir,
                         psString label,
                         psString reduction,
                         psString expgroup,
                         psString dvodb)
{
    PS_ASSERT_PTR_NON_NULL(config, false);

    // start a transaction
    if (!psDBTransaction(config->dbh)) {
        psError(PS_ERR_UNKNOWN, false, "database error");
        return false;
    }
    
    // create a chipRun
    if (!chipRunInsert(config->dbh,
            0x0, // chip_id
            exp_id,
            "run",      // state                
            workdir,
            "dirty",    // workdir_state
            label,
            reduction,
            expgroup,
            dvodb)
    ) {
        // rollback
        if (!psDBRollback(config->dbh)) {
            psError(PS_ERR_UNKNOWN, false, "database error");
        }
        psError(PS_ERR_UNKNOWN, false, "database error");
        return false;
    }

    // point of no return
    if (!psDBCommit(config->dbh)) {
        psError(PS_ERR_UNKNOWN, false, "database error");
        return false;
    }

    return true;
}
