/*
 * Copyright 2002-2005 Uwyn bvba/sprl <info[remove] at uwyn dot com>
 * Distributed under the terms of the GNU Lesser General Public
 * License, v2.1 or later
 *
 * $Id: generic_nosequence.java 1322 2005-02-14 11:16:07Z gbevin $
 */
package com.uwyn.drone.modules.faqmanagement.databasedrivers;

import com.uwyn.drone.core.Bot;
import com.uwyn.drone.modules.exceptions.FaqManagerException;
import com.uwyn.drone.modules.faqmanagement.FaqData;
import com.uwyn.drone.modules.faqmanagement.exceptions.AddFaqErrorException;
import com.uwyn.drone.modules.faqmanagement.exceptions.InstallErrorException;
import com.uwyn.drone.modules.faqmanagement.exceptions.RemoveErrorException;
import com.uwyn.rife.database.Datasource;
import com.uwyn.rife.database.DbConnection;
import com.uwyn.rife.database.DbPreparedStatement;
import com.uwyn.rife.database.DbPreparedStatementHandler;
import com.uwyn.rife.database.exceptions.DatabaseException;
import com.uwyn.rife.database.queries.Query;
import com.uwyn.rife.tools.InnerClassException;
import java.sql.Statement;

public abstract class generic_nosequence extends generic
{
	public generic_nosequence(Datasource datasource)
	{
		super(datasource);
	}
	
	public boolean install()
	throws FaqManagerException
	{
		try
		{
			executeUpdate(mCreateTableFaq);
		}
		catch (DatabaseException e)
		{
			throw new InstallErrorException(e);
		}
		
		return true;
	}

	public int addFaq(final Bot bot, final FaqData faqData)
	throws FaqManagerException
	{
		if (null == bot)		throw new IllegalArgumentException("bot can't be null.");
		if (null == faqData)	throw new IllegalArgumentException("faqData can't be null.");
		if (!faqData.validate())
		{
			throw new AddFaqErrorException(faqData);
		}
		
		final int[] result = new int[] {-1};

		try
		{
			if (0 == executeUpdate(mAddFaq, new DbPreparedStatementHandler() {
					public DbPreparedStatement getPreparedStatement(Query query, DbConnection connection)
					{
						return connection.getPreparedStatement(query, Statement.RETURN_GENERATED_KEYS);
					}
					
					public void setParameters(DbPreparedStatement statement)
					{
						statement
							.setString("botname", bot.getName())
							.setBean(faqData);
					}
					
					public int performUpdate(DbPreparedStatement statement)
					{
						setParameters(statement);
						int query_result = statement.executeUpdate();
						result[0] = statement.getFirstGeneratedIntKey();
						return query_result;
					}
				}))
			{
				throw new AddFaqErrorException(faqData);
			}
		}
		catch (InnerClassException e)
		{
			throw ((FaqManagerException)e.getCause());
		}
		catch (DatabaseException e)
		{
			throw new AddFaqErrorException(faqData, e);
		}
		
		assert result[0] >= 0;

		return result[0];
	}

	public boolean remove()
	throws FaqManagerException
	{
		try
		{
			executeUpdate(mDropTableFaq);
		}
		catch (DatabaseException e)
		{
			throw new RemoveErrorException(e);
		}
		
		return true;
	}
}
