package com.heckmansoft.surjey.model.datastore;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.apache.log4j.Logger;

import com.heckmansoft.surjey.model.vo.Survey;
import com.heckmansoft.surjey.model.vo.ValueObject;

/**
 * Manages object-relational mapping for Survey objects.
 */
public class SurveyDatastore extends Datastore {

    final static String TABLE_NAME = "surveys";
    static final String TABLE_ADD_FIELDS = "description";

    private Logger log = Logger.getLogger(SurveyDatastore.class);

    /**
     * Constructor.
     */
    public SurveyDatastore() {
        super(TABLE_NAME,TABLE_ADD_FIELDS);
    }

    /**
     * Finds a particular survey.
     * @param id Id of the survey to find.
     * @return A Survey instance, or null if no survey found
     */
    public Survey findById(String id) throws DatastoreException {
        log.debug("findById(" + id + ")");
        return ((Survey) extractSingle(selectById(id)));
    }

    /**
     * From the given object, get a list of arguments to use for
     * constructing a query or update.
     * @param vo Object containing data to use.
     * @return A list of arguments.
     */
    protected List getArgs(ValueObject vo) {
        List args = super.getArgs(vo);
        Survey survey = (Survey) vo;
        args.add(survey.getDescription());
        return args;
    }

    /**
     * Extract an object from the given result set.
     * @param results The result set.
     * @return The newly extracted object.
     */
    protected ValueObject extract(ResultSet results) throws DatastoreException {
        try {
            // Create a new survey
            Survey survey = createSurvey();
            super.extract(results, survey);
            survey.setName(results.getString("name"));
            survey.setDescription(results.getString("description"));

            return survey;
        } catch (SQLException e) {
            log.debug(e);
            throw new RuntimeException(e);
        }

    }

    /**
     * Create a new survey.
     * @return newly created survey.
     */
    protected Survey createSurvey() {
        return new Survey();
    }

}
