/*
 * 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.java 1308 2005-02-11 10:30:45Z gbevin $
 */
package com.uwyn.drone.modules.seenmanagement.databasedrivers;

import com.uwyn.drone.core.Bot;
import com.uwyn.drone.core.Channel;
import com.uwyn.drone.modules.exceptions.SeenManagerException;
import com.uwyn.drone.modules.seenmanagement.DatabaseSeen;
import com.uwyn.drone.modules.seenmanagement.SeenData;
import com.uwyn.rife.database.Datasource;
import com.uwyn.rife.database.queries.CreateTable;
import com.uwyn.rife.database.queries.DropTable;
import com.uwyn.rife.database.queries.Insert;
import com.uwyn.rife.database.queries.Select;
import com.uwyn.rife.database.queries.Update;

public class generic extends DatabaseSeen
{
	protected CreateTable	mCreateTableSeen = null;
	protected Select		mGetSeen = null;
	protected Insert		mAddSeen = null;
	protected Update		mUpdateSeen = null;
	protected Select		mSearchSeenMessage = null;
	protected DropTable		mDropTableSeen = null;
	
	public generic(Datasource datasource)
	{
		super(datasource);

		mCreateTableSeen = new CreateTable(getDatasource())
			.table("seen")
			.column("botname", String.class, 30, CreateTable.NOTNULL)
			.column("channel", String.class, 30, CreateTable.NOTNULL)
			.column("servername", String.class, 60, CreateTable.NOTNULL)
			.columns(SeenData.class)
			.primaryKey("SEEN_PK", new String[] {"botname", "channel", "servername", "nickname"});

		mGetSeen = (Select)new Select(getDatasource())
			.from("seen")
			.whereParameter("botname", "=")
			.whereParameterAnd("channel", "=")
			.whereParameterAnd("servername", "=")
			.whereParameterAnd("lower(nickname)", "nickname", "=");

		mAddSeen = new Insert(getDatasource())
			.into("seen")
			.fieldParameter("botname")
			.fieldParameter("channel")
			.fieldParameter("servername")
			.fieldsParameters(SeenData.class);

		mUpdateSeen = (Update)new Update(getDatasource())
			.table("seen")
			.fieldsParameters(SeenData.class)
			.whereParameter("botname", "=")
			.whereParameterAnd("channel", "=")
			.whereParameterAnd("servername", "=")
			.whereParameterAnd("lower(nickname)", "currentnickname", "=");

		mDropTableSeen = new DropTable(getDatasource())
			.table("seen");
	}
	
	public boolean install()
	throws SeenManagerException
	{
		return _install(mCreateTableSeen);
	}

	public void recordSeen(Bot bot, Channel channel, SeenData seenData)
	throws SeenManagerException
	{
		_recordSeen(mAddSeen, mUpdateSeen, bot, channel, seenData);
	}
	
	public SeenData getSeen(Bot bot, Channel channel, String nickname)
	throws SeenManagerException
	{
		return _getSeen(mGetSeen, bot, channel, nickname);
	}
	
	public boolean remove()
	throws SeenManagerException
	{
		return _remove(mDropTableSeen);
	}
}
