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.QuestionType;
import com.heckmansoft.surjey.model.vo.ValueObject;

/**
 * Manages object-relational mapping for QuestionType objects.
 */
public class QuestionTypeDatastore extends Datastore {
    static final String TABLE_NAME = "question_types";
    static final String TABLE_ADD_FIELDS = "description";

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

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

    /**
     * Finds particular question type.
     *
     * @param id Id of the question type to find.
     * @return The QuestionType instance, or null if no match found
     */
    public QuestionType findById(String id) throws DatastoreException {
        log.debug("findById(" + id + ")");
        return ((QuestionType) 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);
        QuestionType questionType = (QuestionType) vo;
        args.add(questionType.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 {
            QuestionType questionType = createQuestionType();
            super.extract(results, questionType);
            questionType.setName(results.getString("name"));
            questionType.setDescription(results.getString("description"));
            return questionType;
        } catch (SQLException e) {
            log.debug(e);
            throw new RuntimeException(e);
        }
    }

    /**
     * Create a new question type.
     * @return newly created question type.
     */
    protected QuestionType createQuestionType() {
        return new QuestionType();
    }

}