//
// C++ Implementation: newentryfromtextdialog
//
// Description: 
//
//
// Author: Thach Nguyen <thach.nguyen@rmit.edu.au>, (C) 2006
//
// Copyright: See COPYING file that comes with this distribution
//
//
#include "newentryfromtextdialog.h"
#include "kbib.h"
#include "kbibdoc.h"
#include <kcombobox.h>
#include <kpushbutton.h>
#include <kpopupmenu.h>
#include <klocale.h>
#include <kiconloader.h>
#include <kfiledialog.h>
#include <kurl.h>
#include <ktempfile.h>
#include <kmessagebox.h>
#include <kio/netaccess.h>
#include <kio/job.h>
#include <kaccelmanager.h>
#include <qhbox.h>
#include <qvbox.h>
#include <qlayout.h>
#include <qwhatsthis.h>
#include <ktextedit.h>
#include <qclipboard.h>
#include <qapplication.h>
#include <qfile.h>
#include <qtextstream.h>


#if HAVE_POPPLER
	#include <poppler-qt.h>
#endif

NewEntryFromTextDialog::NewEntryFromTextDialog(QWidget *parent, const char *name, QString text)
	: KDialogBase( parent, name , true, i18n("New Reference from Plain Text"), KDialogBase::Ok|KDialogBase::Cancel, KDialogBase::Ok, false )
{
	QWidget* page = new QWidget(this);
	setMainWidget(page);
	QVBoxLayout* l = new QVBoxLayout(page, 0, KDialog::spacingHint());
	
	QHBox* box1 = new QHBox(page);
	box1->setSpacing(KDialog::spacingHint());
	

	m_open = new KPushButton(KStdGuiItem::open(), box1);
	connect(m_open, SIGNAL(clicked()), SLOT(slotOpenClicked()));
	QWhatsThis::add(m_open, i18n("Click to set the content of an existing text file into the below text box"));

#if HAVE_POPPLER		
	m_pdf = new KPushButton(i18n("PDF"), box1);
	m_pdf->setGuiItem(KGuiItem(i18n("PDF"),
					   SmallIconSet(QString::fromLatin1("pdf"))));
	connect(m_pdf, SIGNAL(clicked()), SLOT(slotPDFClicked()));
	QWhatsThis::add(m_pdf, i18n("Click to copy text content of a PDF file into the below text box"));
#endif	
	m_paste = new KPushButton(i18n("Paste"), box1);
	m_paste->setGuiItem(KGuiItem(i18n("Paste"),
					   SmallIconSet(QString::fromLatin1("editpaste"))));
	connect(m_paste, SIGNAL(clicked()), SLOT(slotPasteClicked()));
	QWhatsThis::add(m_paste, i18n("Click to paste the clipboard content into the below text box"));
	
	
	m_clear = new KPushButton(KStdGuiItem::clear(), box1);
	connect(m_clear, SIGNAL(clicked()), SLOT(slotClearClicked()));
	QWhatsThis::add(m_clear, i18n("Click to clear the content of the below text box"));

	
	
	box1->setStretchFactor(new QWidget(box1),1);
	
	m_entryType = new KComboBox(false, box1);
	QWhatsThis::add(m_entryType, i18n("Select the reference type"));

	
	l->addWidget(box1);
	
	m_edit = new KTextEdit(page);
	l->addWidget(m_edit);
	m_edit->setMinimumWidth(400);
	m_edit->setMinimumHeight(300);
	connect(m_edit, SIGNAL(selectionChanged()), SLOT(slotSelectionChanged()));
	m_entryType->insertStringList(BibEntryDefTable::self()->getEntryDefNames());
	
	connect(m_entryType, SIGNAL(activated(int )), SLOT(slotEntryTypeChange(int)));
	
	
	entryPreview = new KTextEdit(page);
	entryPreview->setReadOnly(TRUE);
	entryPreview->setMinimumHeight(200);
	l->addWidget(entryPreview);
	
	
	m_fieldMenu = new KPopupMenu(this);
	setToFieldSubMenu = new KPopupMenu(this);
	addToFieldSubMenu = new KPopupMenu(this);
	m_fieldMenu->insertItem(i18n("Set Selected Text to ... "), setToFieldSubMenu);
	m_fieldMenu->insertItem(QIconSet ( SmallIcon ( "edit_add" ) ), i18n("Add Selected Text to ... "), addToFieldSubMenu);
	
		
	connect(setToFieldSubMenu, SIGNAL(activated(int)),
			this, SLOT(slotSetFieldMenuActivated(int)));
	
	connect(addToFieldSubMenu, SIGNAL(activated(int)),
			this, SLOT(slotAddFieldMenuActivated(int)));

	
	m_edit->setText(text);
	m_edit->getCursorPosition(0,0);	
	m_edit->setFocus();
	KAcceleratorManager::manage(page);
	
	m_entryType->setCurrentItem(0);
	m_entry = new BibEntry( m_entryType->text(0) , "");
	slotEntryTypeChange(0);
}


NewEntryFromTextDialog::~NewEntryFromTextDialog()
{
	if (m_entry)
		delete m_entry;
}

void NewEntryFromTextDialog::slotClearClicked()
{
	m_edit->clear();	
}
void NewEntryFromTextDialog::slotOpenClicked()
{
	KURL url = KFileDialog::getOpenURL(QString::fromLatin1(":open"), i18n("*.*|All files"),
									   this, i18n("Open File..."));
	if (!url.isEmpty())
	{
		KTempFile tmpfile;
		tmpfile.setAutoDelete(TRUE);
		QString fn = tmpfile.name();
		if(!KIO::NetAccess::download(url, fn, this))
		{
			QString str;
			if(url.isLocalFile())
			{
				str = i18n("Kbib is unable to find the file - %1.").arg(url.fileName());
			}
			else
			{
				str = i18n("Kbib is unable to download the file - %1.").arg(url.url());
			}
			KMessageBox::sorry(this, str);

			return;
			
		}
		QFile file(fn); // Read the text from a file
		if ( file.open( IO_ReadOnly ) ) {
			QTextStream stream( &file );
			m_edit->setText( stream.read() );
			m_edit->getCursorPosition(0,0);	
		}
	}
	

}

void NewEntryFromTextDialog::slotPasteClicked()
{
	m_edit->paste();
	m_edit->getCursorPosition(0,0);	
}


void NewEntryFromTextDialog::slotPDFClicked()
{
#if HAVE_POPPLER	
	QString filter = i18n("*.pdf|PDF files (*.pdf)");
    filter += QString::fromLatin1("\n");
    filter += i18n("*|All files");
	QString fn = KFileDialog::getOpenFileName(QString::fromLatin1(":open"), filter,
                                           this, i18n("Open File..."));
	
	if (fn.isEmpty())
		return;
	
	Poppler::Document *doc = Poppler::Document::load(fn);
	if (!doc){
		KMessageBox::error( this,i18n("The file cannot be openned."));
		return;	
	}
	int numPages = doc->getNumPages();
	QString st = QString::null;
	for (int i = 0; i < 1; i++){
		Poppler::Page *page = doc->getPage(i);
		st = st + page->getText(0);	
	}
	m_edit->setText(st);
	m_edit->getCursorPosition(0,0);	
	m_entry->setField(QString::fromLatin1("file"), fn);
#endif
}



void NewEntryFromTextDialog::slotSelectionChanged()
{
	if (m_edit->hasSelectedText() ){
		m_fieldMenu->popup(QCursor::pos());
	}
}

void NewEntryFromTextDialog::slotEntryTypeChange(int index){
	setToFieldSubMenu->clear();
	addToFieldSubMenu->clear();
	
	int addFieldMenuIdx = 0;
	
	QString type = m_entryType->text(index);
	
	BibEntry *new_entry = new BibEntry(type, "");
	QString key = m_entry->getKey();
	new_entry->setKey(key );
	new_entry->setIndex(m_entry->getIndex());
	new_entry->setFields(*m_entry);

	delete m_entry;

	m_entry = new BibEntry(*new_entry);
	delete new_entry;
		
	BibEntryDef *entryType = BibEntryDefTable::self()->getBibEntryDef(type);
	int nrq = entryType->numRequired();
	setToFieldSubMenu->insertItem(QString::fromLatin1("Citation key"), 0);

	for (int i = 0; i < nrq; i++){
		QString fn = QString::fromLatin1(entryType->getRequired(i));
		
		if (fn != QString::fromLatin1("lockkey")){
			setToFieldSubMenu->insertItem(fn, i+1);	
		}
		RefField *field = BibEntryDefTable::self()->getRefField ( fn );
		int type;
		if ( field )
			type = field->type;
		else
			type = TEXT;
		if (type == MULTIPLE){
			addToFieldSubMenu->insertItem(fn, addFieldMenuIdx);
			addFieldMenuIdx++;	
		}
			
		
	}
	setToFieldSubMenu->insertSeparator();
	addToFieldSubMenu->insertSeparator();
	int nopt = entryType->numOptional();
	for (int i = 0; i < nopt; i++){
		QString fn = QString::fromLatin1(entryType->getOptional(i));
		if (fn != QString::fromLatin1("lockkey")){
			setToFieldSubMenu->insertItem(fn, i+nrq+1);	
		}
		
		RefField *field = BibEntryDefTable::self()->getRefField ( fn );
		int type;
		if ( field )
			type = field->type;
		else
			type = TEXT;
		if (type == MULTIPLE){
			addToFieldSubMenu->insertItem(fn, addFieldMenuIdx);
			addFieldMenuIdx++;	
		}
	}
	int id =  m_fieldMenu->idAt (1); 
	if (addToFieldSubMenu->count () > 1)
		m_fieldMenu->setItemEnabled(id, true);
	else
		m_fieldMenu->setItemEnabled(id, false);
	
	KBibApp *win = (KBibApp *) (this->parent() );
	KBibDoc *doc = win->getDocument();	
	entryPreview->setText(doc->getEntryList()->detailedEntry(m_entry) );
}


void NewEntryFromTextDialog::slotSetFieldMenuActivated(int idx){
	QString text = (m_edit->selectedText() ).stripWhiteSpace();
	QString field = setToFieldSubMenu->text(idx);
	
	if (field == QString::fromLatin1("Citation key") ){
		m_entry->setKey(text );	
	}
	else{
		m_entry->setField(field, text );	
	}

	m_edit->removeSelection();
	KBibApp *win = (KBibApp *) (this->parent() );
	KBibDoc *doc = win->getDocument();	
	entryPreview->setText(doc->getEntryList()->detailedEntry(m_entry) );
}


void NewEntryFromTextDialog::slotAddFieldMenuActivated(int idx){
	QString text = (m_edit->selectedText() ).stripWhiteSpace();
	QString fn = addToFieldSubMenu->text(idx);
	QString fieldText = m_entry->getField(fn);
	if (fieldText.isEmpty()){
		m_entry->setField(fn, text );	
	}
	else if (!text.isEmpty()){
		RefField *field = BibEntryDefTable::self()->getRefField ( fn );
		QString newText = fieldText + field->connectingString + text;
		m_entry->setField(fn, newText );	
	}
	fieldText = m_entry->getField(fn);
	
	m_edit->removeSelection();
	KBibApp *win = (KBibApp *) (this->parent() );
	KBibDoc *doc = win->getDocument();	
	entryPreview->setText(doc->getEntryList()->detailedEntry(m_entry) );
	
}

#include "newentryfromtextdialog.moc"
