/*********
*
* This file is part of BibleTime's source code, http://www.bibletime.info/.
*
* Copyright 1999-2006 by the BibleTime developers.
* The BibleTime source code is licensed under the GNU General Public License version 2.0.
*
**********/


//BibleTime includes
#include "ckeychooserwidget.h"

//BibleTime frontend includes
#include "frontend/cbtconfig.h"


//TQt includes
#include <tqlineedit.h>
#include <tqstring.h>
#include <tqstringlist.h>
#include <tqlistbox.h>
#include <tqtoolbutton.h>
#include <tqevent.h>
#include <tqlayout.h>
#include <tqpainter.h>
#include <tqstyle.h>
#include <tqpixmap.h>
#include <tqapplication.h>
#include <tqtooltip.h>
#include <tqrect.h>

CKCComboBox::CKCComboBox(bool rw,TQWidget* parent,const char* name)
: TQComboBox(rw,parent,name) {
	setFocusPolicy(TQWidget::WheelFocus);
	if (lineEdit()) {
		installEventFilter( lineEdit() );
	}
}

/** Reimplementation. */
bool CKCComboBox::eventFilter( TQObject *o, TQEvent *e ) {
	if (e->type() == TQEvent::FocusOut) {
		TQFocusEvent* f = static_cast<TQFocusEvent*>(e);

		if (o == lineEdit() && f->reason() == TQFocusEvent::Tab) {
			int index = listBox()->index( listBox()->findItem(currentText()) );
			if (index == -1) {
				index = 0;// return 0 if not found
			}
			setCurrentItem( index );
			emit focusOut( index );

			return false;
		}
		else if (f->reason() == TQFocusEvent::Popup) {
			return false;
		}
		else if (f->reason() == TQFocusEvent::ActiveWindow) {
			emit activated(currentText());
			return false;
		}
		else if (f->reason() == TQFocusEvent::Mouse) {
			emit activated(currentText());
			return false;
		}
		else if (o == this) {
			emit activated(currentText());
			return false;
		}
	}

	return TQComboBox::eventFilter(o,e);
}

/** Scrolls in the list if the wheel of the mouse was used. */
void CKCComboBox::wheelEvent( TQWheelEvent* e ) {
	return TQComboBox::wheelEvent(e);

	const signed int change = (int)((float)e->delta()/(float)120);
	int current = currentItem();

	if ((current+change >= 0) && (current+change<count()) ) {
		setCurrentItem(current+change);
		e->accept();
		emit activated( currentItem() );
	}
	else {
		e->ignore();
	}
}

//**********************************************************************************/

CKeyChooserWidget::CKeyChooserWidget(int count, const bool useNextPrevSignals,  TQWidget *parent, const char *name) : TQWidget(parent,name) {
	m_useNextPrevSignals = useNextPrevSignals;

	for (int index=1; index <= count; index++) {
		m_list.append( TQString::number(index) );
	}
	init();
	reset(m_list,0,false);
};

CKeyChooserWidget::CKeyChooserWidget(TQStringList *list, const bool useNextPrevSignals, TQWidget *parent, const char *name ) : TQWidget(parent,name) {
	m_useNextPrevSignals = useNextPrevSignals;

	if (list) {
		m_list = *list; //deep copy the items of list
	}
	else {
		m_list.clear();
	}

	init();
	reset(m_list,0,false);
}

void CKeyChooserWidget::reset(const int count, int index, bool do_emit) {
	if (!isUpdatesEnabled())
		return;

	m_list.clear();
	for (int i=1; i <= count; i++) { //TODO: CHECK
		m_list.append( TQString::number(i) );
	}

	reset(&m_list,index,do_emit);
}

void CKeyChooserWidget::reset(TQStringList& list, int index, bool do_emit) {
	if (!isUpdatesEnabled())
		return;

	m_list = list;
	reset(&m_list,index,do_emit);
}


void CKeyChooserWidget::reset(TQStringList *list, int index, bool do_emit) {
	if (isResetting || !isUpdatesEnabled())
		return;

	//  tqWarning("starting insert");
	isResetting = true;

	oldKey = TQString();

	//  m_comboBox->setUpdatesEnabled(false);
	//DON'T REMOVE THE HIDE: Otherwise TQComboBox's sizeHint() function won't work properly
	m_comboBox->hide();
	m_comboBox->clear();
	if (list) {
		m_comboBox->insertStringList(*list);
	}

	if (!list || (list && !list->count())) { //nothing in the combobox
		setEnabled(false);
	}
	else if (!isEnabled()) { //was disabled
		setEnabled(true);
	}

	if (list->count()) {
		m_comboBox->setCurrentItem(index);
	}
	if (do_emit) {
		emit changed(m_comboBox->currentItem());
	}

	const TQSize dummySize = m_comboBox->sizeHint(); //without this function call the combo box won't be properly sized!
	//DON'T REMOVE OR MOVE THE show()! Otherwise TQComboBox's sizeHint() function won't work properly!
	m_comboBox->show();

	//  m_comboBox->setFont( m_comboBox->font() );
	//  m_comboBox->setUpdatesEnabled(true);

	isResetting = false;
	//  tqWarning("inserted");
}

/** Initializes this widget. We need this function because we have more than one constructor. */
void CKeyChooserWidget::init() {
	oldKey = TQString();

	setFocusPolicy(TQWidget::WheelFocus);

	m_comboBox = new CKCComboBox( true, this );
	m_comboBox->setAutoCompletion( true );
	m_comboBox->setInsertionPolicy(TQComboBox::NoInsertion);
	m_comboBox->setFocusPolicy(TQWidget::WheelFocus);

	m_mainLayout = new TQHBoxLayout( this );
	m_mainLayout->addWidget(m_comboBox,5);

	m_scroller = new CScrollerWidgetSet(this);

	m_mainLayout->addWidget( m_scroller );
	m_mainLayout->addSpacing(2);

	setTabOrder(m_comboBox, 0);

	connect(m_scroller, TQ_SIGNAL(scroller_pressed()), TQ_SLOT(lock()));
	connect(m_scroller, TQ_SIGNAL(scroller_released()), TQ_SLOT(unlock()));
	connect(m_scroller, TQ_SIGNAL(change(int)), TQ_SLOT(changeCombo(int)) );

	connect(m_comboBox, TQ_SIGNAL(activated(int)), TQ_SLOT(slotComboChanged(int)));
	//  connect(m_comboBox, TQ_SIGNAL(activated(const TQString&)), TQ_SLOT(slotReturnPressed(const TQString&)));
	connect(m_comboBox->lineEdit(), TQ_SIGNAL(returnPressed()), TQ_SLOT(slotReturnPressed()));
	connect(m_comboBox, TQ_SIGNAL(focusOut(int)), TQ_SIGNAL(focusOut(int)));

	updatelock = false;
	isResetting = false;
}

/** Is called when the return key was presed in the combobox. */
void CKeyChooserWidget::slotReturnPressed( /*const TQString& text*/) {
	Q_ASSERT(comboBox()->lineEdit());
	tqWarning("return pressed");

	TQString text = comboBox()->lineEdit()->text();
	for (int index = 0; index < comboBox()->count(); ++index) {
		if (comboBox()->text(index) == text) {
//			emit changed(index);
			emit focusOut(index); // a workaround because focusOut is not checked, the slot connected to changed to check
			break;
		}
	}
}

/** Is called when the current item of the combo box was changed. */
void CKeyChooserWidget::slotComboChanged(int index) {
	tqWarning("CKeyChooserWidget::slotComboChanged(int index)");
	if (!isUpdatesEnabled()) {
		return;
	}

	setUpdatesEnabled(false);

	const TQString key = comboBox()->text( index );
	if (oldKey.isNull() || (oldKey != key)) {
		emit changed(index);
	}

	oldKey = key;

	setUpdatesEnabled(true);
}

/** Sets the tooltips for the given entries using the parameters as text. */
void CKeyChooserWidget::setToolTips( const TQString comboTip, const TQString nextEntryTip, const TQString scrollButtonTip, const TQString previousEntryTip) {
	TQToolTip::add (comboBox(),comboTip);
	m_scroller->setToolTips(nextEntryTip, scrollButtonTip, previousEntryTip);
}

/** Sets the current item to the one with the given text */
bool CKeyChooserWidget::setItem( const TQString item ) {
	bool ret = false;
	const int count = comboBox()->count();
	for (int i = 0; i < count; ++i) {
		if (comboBox()->text(i) == item) {
			comboBox()->setCurrentItem(i);
			ret = true;
			break;
		}
	}
	if (!ret)
		comboBox()->setCurrentItem(-1);
	return ret;
}

/* Handlers for the various scroller widgetset. */
void CKeyChooserWidget::lock() {
	updatelock = true;
	comboBox()->setEditable(false);
	oldKey = comboBox()->currentText();
}

void CKeyChooserWidget::unlock() {
	updatelock = false;
	comboBox()->setEditable(true);
	comboBox()->setEditText(comboBox()->text(comboBox()->currentItem()));
	if (comboBox()->currentText() != oldKey) {
		emit changed(comboBox()->currentItem());
	}
}

void CKeyChooserWidget::changeCombo(int n) {
	const int old_item = comboBox()->currentItem();
	int new_item = old_item + n;

	//index of highest Item
	const int max = comboBox()->count()-1;
	if(new_item > max) new_item = max;
	if(new_item < 0) new_item = 0;

	if(new_item != old_item) {
		comboBox()->setCurrentItem(new_item);
		if(!updatelock)
			emit changed(new_item);
	}
}

#include "ckeychooserwidget.moc"
