/***************************************************************************
                          html_widget.cpp  -  description
                             -------------------
    begin                : December 2007
    copyright            : (c) 2007 by Iven Wold - 526f6c616e642053756368616e
    email                : hour.glass2@yahoo.com
    license              : GPL v 2.0
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   This file is part of QTrans.                                          *
 *                                                                         *
 *   QTrans is free software; you can redistribute it and/or modify        *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; version 2 of the License.               *
 *                                                                         *
 *   QTrans is distributed in the hope that it will be useful,             *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with QTrans. If not, see <http://www.gnu.org/licenses/> or      *
 *   write to the Free Software Foundation, Inc.,                          *
 *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA.         *
 *                                                                         *
 ***************************************************************************/


//#include <QWebPage>	//ooo

//#include <KDebug>		//ooo
#include <QDebug>		//x
#include <QTextCodec>		//ooo
#include <QByteArray>		//ooo
#include <KWindowSystem>	//ooo

#include "html_widget.h"
#include "utils.h"
#include "qtrans.h"


Html_Widget::Html_Widget(QWidget *parent, bool *saveTranslation, bool *compactMode, bool *stayOnTop, bool *enableAlternates, bool *wordStartsWith, bool *wholeWordsOnly, bool *wholeStarDict, QList<Dictionary> *bab_dict, bool *enabled)	//ooo
	//: QWebView(parent)
	//: QWebView(parent),				//ooo
    : QWebEngineView(parent),				//xxx
          saveTranslation_(saveTranslation),		//ooo
	  compactMode_(compactMode),			//ooo
          stayOnTop_(stayOnTop),			//ooo
          enableAlternates_(enableAlternates),		//ooo
          wordStartsWith_(wordStartsWith),		//ooo
          wholeWordsOnly_(wholeWordsOnly),		//ooo
          wholeStarDict_(wholeStarDict),		//ooo
          bab_dict_(bab_dict),				//ooo
          enabled_(enabled)				//ooo
{

	Par = parent;				//ooo
	//view()->setMinimumSize(60,60);
	clear();
    
    QIcon::setThemeName("oxygen");  //x

	//saveOutputAct_ = new QAction(KIcon("document-save"), i18n("Save output"), this);			//ooo
    saveOutputAct_ = new QAction(QIcon::fromTheme("document-save"), i18n("Save output"), this);			//x
	//saveOutputAct_ = new QAction(KIcon("edit-bomb"), i18n("Save output"), this);				//ooo
	saveOutputAct_->setShortcut(tr("Ctrl+S"));								//ooo
	saveOutputAct_->setIconVisibleInMenu(true);								//ooo
	connect( saveOutputAct_, SIGNAL(triggered()), this, SLOT(slot_saveTranslation()) );			//ooo

	//normalModeAct_ = new QAction( KIcon("view-fullscreen"), i18n("&Normal Mode"), this );			//ooo
    normalModeAct_ = new QAction( QIcon::fromTheme("view-fullscreen"), i18n("&Normal Mode"), this );			//x
	normalModeAct_->setIconVisibleInMenu(true);								//ooo
	//compactModeAct_ = new QAction( KIcon("view-restore"), i18n("&Compact Mode"), this );			//ooo
    compactModeAct_ = new QAction( QIcon::fromTheme("view-restore"), i18n("&Compact Mode"), this );			//x
	compactModeAct_->setIconVisibleInMenu(true);								//ooo

	connect( compactModeAct_, SIGNAL(triggered()), SLOT(slot_changeModeSelected()) );			//ooo
	connect( normalModeAct_,  SIGNAL(triggered()), SLOT(slot_changeModeSelected()) );			//ooo

	stayOnTopAct_ = new QAction( i18n("&Stay on Top"), this );						//ooo	
	stayOnTopAct_->setCheckable(true);

	alternatesAct_ = new QAction( i18n("&Enable Alternates (BGL)"), this );					//ooo
	alternatesAct_->setCheckable(true);

	wordStartsWithAct_ = new QAction( i18n("&Word begins with ..."), this );				//ooo
	wordStartsWithAct_->setCheckable(true);
	wholeWordsOnlyAct_ = new QAction( i18n("&Whole words only"), this );					//ooo
	wholeWordsOnlyAct_->setCheckable(true);

	lookUpInWholeStarDictAct_ = new QAction( i18n("&Look up in whole StarDict"), this );			//ooo
	lookUpInWholeStarDictAct_->setCheckable(true);
	lookUpInWholeStarDictAct_->setIconVisibleInMenu(true);

	//searchAllAct_ = new QAction( KIcon("edit-find"), i18n("&Look up in all dic"), this );			//ooo
    searchAllAct_ = new QAction( QIcon::fromTheme("edit-find"), i18n("&Look up in all dic"), this );			//x
	searchAllAct_->setIconVisibleInMenu(true);
	//searchEveryDictAct_ = new QAction( KIcon("system-search"), i18n("&Look up in hidden too"), this );	//ooo
    searchEveryDictAct_ = new QAction( QIcon::fromTheme("system-search"), i18n("&Look up in hidden too"), this );	//x
	searchEveryDictAct_->setIconVisibleInMenu(true);

	disableAct_ = new QAction( i18n("&Disable"), this );							//ooo
	disableAct_->setIconVisibleInMenu(true);								//ooo
	enableAct_ = new QAction( i18n("&Enable"), this );							//ooo
	enableAct_->setIconVisibleInMenu(true);									//ooo

	connect( stayOnTopAct_, SIGNAL(triggered()), SLOT(slot_OnTop()) );					//ooo
	//connect( stayOnTopAct_, SIGNAL(triggered()), emit stayOnTopSelected() );				//ooo
	connect( alternatesAct_, SIGNAL(triggered()), SLOT(slot_Alternates()) );				//ooo
	connect( wordStartsWithAct_, SIGNAL(triggered()), SLOT(slot_WordStartsWith()) );			//ooo
	connect( wholeWordsOnlyAct_, SIGNAL(triggered()), SLOT(slot_WholeWordsOnly()) );			//ooo
	connect( lookUpInWholeStarDictAct_, SIGNAL(triggered()), SLOT(slot_LookUpInWholeDictionary()) );	//ooo
	connect( searchAllAct_, SIGNAL(triggered()), SLOT(slot_searchInAllDictionaries()) );			//ooo
	connect( searchEveryDictAct_, SIGNAL(triggered()), SLOT(slot_searchInEveryDictionary()) );		//ooo
	connect( disableAct_, SIGNAL(triggered()), SLOT(slot_Enable()) );					//ooo
	connect( enableAct_, SIGNAL(triggered()), SLOT(slot_Enable()) );					//ooo

}


Html_Widget::~Html_Widget()
{
}


void Html_Widget::slot_saveTranslation()
{

	if (*saveTranslation_) {
		emit saveTranslationSelected();
	}

}

void Html_Widget::slot_changeModeSelected()
{
	if (*compactMode_) {
		emit changeModeSelected();
	} else {
		emit changeModeSelected();
	}
}


void Html_Widget::slot_languageFromLanguagemenuSelected(QAction *action)
{
	for (int i = 0; i < actionsList_.size(); ++i) {
		if (action == actionsList_.at(i)) {
			emit languageFromLanguagemenuSelected_(i);
			break;
		}
	}
}


void Html_Widget::slot_stayOnTopSelected()
{
	emit stayOnTopSelected();
}


void Html_Widget::slot_OnTop()
{
	if (!*stayOnTop_) {
		emit stayOnTopSelected();
	} else {
		emit stayOnTopSelected();
	}
}


void Html_Widget::slot_Alternates()
{
	if (!*enableAlternates_) {
		emit alternatesSelected();
	} else {
		emit alternatesSelected();
	}
}


void Html_Widget::slot_WordStartsWith()
{
	if (!*wordStartsWith_) {
		emit wordStartsWithSelected();
	} else {
		emit wordStartsWithSelected();
	}
}


void Html_Widget::slot_WholeWordsOnly()
{
	if (!*wholeWordsOnly_) {
		emit wholeWordsOnlySelected();
	} else {
		emit wholeWordsOnlySelected();
	}
}


void Html_Widget::slot_LookUpInWholeDictionary()
{
	if (!*wholeStarDict_) {
		emit lookUpInWholeDictionarySelected();
	} else {
		emit lookUpInWholeDictionarySelected();
	}
}


void Html_Widget::slot_searchInAllDictionaries()
{
	emit searchInAllDictionariesSelected();
}


void Html_Widget::slot_searchInEveryDictionary()
{
	emit searchInEveryDictionarySelected();
}


void Html_Widget::slot_Enable()
{
	if (*enabled_) {
		emit enabledSelected();
	} else {
		emit enabledSelected();
	}
}


void Html_Widget::contextMenuEvent(QContextMenuEvent *event)
{
	if ( QContextMenuEvent::Mouse) {

		QMouseEvent *event;
	}

	//saveOutputAct_ = new QAction(KIcon("document-save"), i18n("Save output"), this);	//ooo

	findAct = new QAction(i18n("Find"), this);
	findAct->setShortcut(tr("Ctrl+F"));
	connect(findAct, SIGNAL(triggered()), this, SLOT(slot_findMenu()));

	/*saveOutputAct_ = new QAction(KIcon("document-save"), i18n("Save output"), this);	//ooo
	saveOutputAct_->setShortcut(tr("Ctrl+S"));						//ooo
	saveOutputAct_->setIconVisibleInMenu(true);						//ooo
	connect( saveOutputAct_, SIGNAL(triggered()), this, SLOT(slot_saveTranslation()) );	//ooo
*/
	languageMenu_ = new QMenu(this);

	//languageMenu_.addAction(pageAction(QWebPage::Back));
	//languageMenu_.addAction(pageAction(QWebPage::Forward));
	//languageMenu_.addAction(pageAction(QWebPage::Reload));
	//languageMenu_->addAction(pageAction(QWebPage::Copy));    //ooo
    languageMenu_->addAction(pageAction(QWebEnginePage::Copy));   //xx
	languageMenu_->addAction(findAct);
	//languageMenu_->addAction(pageAction(QWebPage::CopyLinkToClipboard)); //ooo
    languageMenu_->addAction(pageAction(QWebEnginePage::CopyLinkToClipboard));  //xx
	//languageMenu_->addAction(pageAction(QWebPage::OpenLinkInNewWindow));		//ooo
	#if QT_VERSION >= 0x040500
		//languageMenu_->addAction(pageAction(QWebPage::SelectAll));		//ooo   Qt 4.5.0    //ooo
        languageMenu_->addAction(pageAction(QWebEnginePage::SelectAll));		//ooo   Qt 4.5.0    //xx
	#endif

	languageMenu_->addSeparator();
	languageMenu_->addAction(saveOutputAct_);
	languageMenu_->addSeparator();

	QList<Dictionary>::const_iterator itr;	//ooo
	int i = 0;
	int j = 0;

	languageGroup_ = new QActionGroup(this);

	//KStandardDirs sd;    //o
	//QStringList dirsPath = sd.findDirs("data","qtrans/flags");   //o
    QStringList dirsPath = QStandardPaths::locateAll(QStandardPaths::GenericDataLocation, QString("qtrans/flags"), QStandardPaths::LocateDirectory);  //x

	QStringList::const_iterator it = dirsPath.constBegin();

	QString flagPath;

	if ( it != dirsPath.constEnd() )
		flagPath = (*it);

	for (itr = bab_dict_->constBegin(); itr != bab_dict_->constEnd(); ++itr) {
		QAction *action;
		//action = new QAction(QIcon(QPixmap(flagPath+Flag[(*itr).flagID])), (*itr).Language, this);  //o
        action = new QAction(QIcon(QPixmap(flagPath+"/"+Flag[(*itr).flagID])), (*itr).Language, this);  //x
		action->setIconVisibleInMenu(true);
		 //languageMenu_->addAction(QIcon(QPixmap(flagPath+Flag[(*it).flagID])), (*itr).Language);
		//languageMenu_->addAction(action);
		actionsList_.append(action);
		j++;
	}

	for (itr = bab_dict_->constBegin(); itr != bab_dict_->constEnd(); ++itr) {
		if ((*itr).disableID) {
			actionsList_.at(i)->setVisible(false);
		}
		//languageMenu->addAction(actionsList.at(i));
		languageGroup_->addAction(actionsList_.at(i));
		i++;
	}

	languageMenu_->addActions(actionsList_);
	languageMenu_->addSeparator();
	if (*compactMode_) {
		languageMenu_->addAction(normalModeAct_);
	} else {
		languageMenu_->addAction(compactModeAct_);
	}
	languageMenu_->addSeparator();
	languageMenu_->addAction(stayOnTopAct_);
	languageMenu_->addAction(alternatesAct_);
	languageMenu_->addSeparator();
	languageMenu_->addAction(wordStartsWithAct_);
	languageMenu_->addAction(wholeWordsOnlyAct_);
	languageMenu_->addAction(lookUpInWholeStarDictAct_);
	languageMenu_->addAction(searchAllAct_);
	languageMenu_->addAction(searchEveryDictAct_);
	languageMenu_->addSeparator();
	if (*enabled_) {
		languageMenu_->addAction(disableAct_);
	} else {
		languageMenu_->addAction(enableAct_);
	}

	//connect(languageGroup_, SIGNAL(triggered(QAction *)), this, SLOT(slot_chooseLibrary(QAction *)));

	//connect(openAct, SIGNAL(triggered()), this, SLOT(open()));
	connect(languageGroup_, SIGNAL(triggered(QAction *)), this, SLOT(slot_languageFromLanguagemenuSelected(QAction *)));

	languageMenu_->exec(mapToGlobal(event->pos()));

	actionsList_.clear();		//ooo
	delete languageGroup_;
	//languageMenu_->clear();	//ooo
	delete languageMenu_;		//ooo
}


void Html_Widget::slot_findMenu()
{
	FindWidget *wdgFind = new FindWidget(this);
	wdgFind->show();
}


void Html_Widget::buildMenu()	//ooo
{
	//popMenu->insertSeparator();
	//popMenu->insertItem(SmallIcon("window_nofullscreen.png"),i18n("&Compact Mode"),
	//			/*Par,SLOT(toggleMode()),*/0);	
	//popMenu->insertItem(i18n("&Stay on Top"),/*Par,SLOT(slot_OnTop()),*/1);
	//popMenu->insertSeparator();
	//popMenu->insertItem(i18n("&Disable"),/*Par,SLOT(slot_Enable()),*/2);

	//popMenu->insertSeparator();
	//popMenu->insertItem(SmallIcon("window_nofullscreen.png"),i18n("&Compact Mode"),
	//			/*Par,SLOT(toggleMode()),*/0);	
	//popMenu->insertItem(i18n("&Stay on Top"),/*Par,SLOT(slot_OnTop()),*/1);
	//popMenu->insertSeparator();
	//popMenu->insertItem(i18n("&Disable"),/*Par,SLOT(slot_Enable()),*/2);
}

/*-- Write the result of translation in the widget --*/
void Html_Widget::setOut(QString S)	//ooo
{
	int mode_;

	if (S=="") {
		clear();
		return;
	}
	
	S = "<!DOCTYPE HTML PUBLIC ""-//W3C//DTD HTML 4.0 Transitional//EN"">"			//ooo
	//S = "<html>\n<style type=""text/css""><!-- i {color: blue} "
	/*S =*/ "<html>"											//ooo
		 "<style type=""text/css""><!-- "							//ooo
		//"span.foreground {color: #ff0000} "							//ooo
		"i {color: "+sentencePartTxtColor+"} "							//ooo
		//"FONT {font-size: 12 pt}"								//ooo
		//"FONT[SIZE~='-1'] {font-size: 12 pt}"							//ooo
		"FONT[SIZE~='-1'] {font-size: "+QString::number(Size-1)+" pt}"				//ooo
		"FONT[SIZE~='-2'] {font-size: "+QString::number(Size-2)+" pt}"				//ooo
		//"abr {color: red} "									//ooo	StarDict
		//"l {color: black} "	//ooo
		"l {color: "+expressionTxtColor+"} "							//ooo
		"k {color: "+expressionTxtColor+"} "							//ooo	StarDict
		"body {font-family: "+fontName+"; background: "+bgColor+"; color: "+txtColor+"; "
		"font-style: "+fontStyle+"; font-weight: "+fontWeight+"; "				//ooo
		"font-size: "+QString::number(Size)+"pt}"
		"p {margin: 0 0 0 0}"
		"p.text {margin: 0 0 0 1.2em; text-indent: -1.2em}"
		"hr {width: 25%}"
		//"a:link {color: black}"
		"a:link {color: "+expressionTxtColor+"}"						//ooo
		//"a:visited {color: black}--></style>\n"
		"a:visited {color: "+expressionTxtColor+"}--></style>\n"				//ooo
		//"<meta http-equiv=""Content-Type"" content=""text/html; charset="+Charset+""">"
		//"<meta http-equiv=""Content-Type"" content=""text/html; charset="+Charset+""">"		//ooo
		//"</head><body>"									//ooo
		"<body>"
		+S+
		//"</body></html>";
		"</body>"										//ooo
	    "</html>";											//ooo
	setHtml(S);		//ooo
}


void Html_Widget::clear()	//ooo
{
	setHtml("<html><body bgcolor="""+bgColor+"""></body></html>");	//ooo
}


void Html_Widget::slot_PopupMenu(QAction *)	//ooo
{
	QMessageBox::about(Par, i18n("About Menu"), QString("%1").arg("Out"));
}


void Html_Widget::setFont(QString family, int pointSize, QFont::Style fontStyle_, int fontWeight_, QString CS)	//ooo
{
	fontName = family;
	Size = pointSize;
	Size_less1 = pointSize-1;	//ooo
	//Size_less1 = 2;		//ooo
	Size_less2 = pointSize-2;	//ooo

	if (fontStyle_ == QFont::StyleItalic) {
		fontStyle = "italic";
	} else {
		fontStyle = "normal";
	}

	if (fontWeight_ == 75) {
		fontWeight = "bold";
	} else {
		fontWeight = "normal";
	}

	Charset = CS;
}


FindWidget::FindWidget(Html_Widget *parent) : QWidget(parent, Qt::Dialog)
{
	Par2 = parent;

	setWindowModality(Qt::WindowModal);
	setWindowTitle(i18n("Find Text"));

	setMinimumSize(300, 150);
	resize(240, 200);

	mainLayout = new QVBoxLayout(this);
	Box1 = new QHBoxLayout(this);
	Label1 = new QLabel(i18n("Text to find:"),this);
	wordName = new QLineEdit(this);

	Box1->setSpacing(5);
	Box1->addWidget(Label1);
	Box1->addWidget(wordName);

	checkBox1  = new QCheckBox("Highlight all existing occurrences", this);
	checkBox2 = new QCheckBox("Case sensitive", this);
	checkBox3 = new QCheckBox("Find backwords", this);

	Box4 = new QHBoxLayout(this);
	bOk = new QPushButton(i18n("&OK"),this);
	bOk->setDefault(true);
	bCancel = new QPushButton(i18n("&Cancel"),this);
	Box4->setSpacing(5);
	Box4->addStretch();
	Box4->addWidget(bOk);
	Box4->addWidget(bCancel);

	wordName->setText(Par2->selectedText());

	//mainLayout->addLayout(Box1);
	mainLayout->addWidget(Label1);
	//mainLayout->setSpacing(1);
	mainLayout->addWidget(wordName);
	mainLayout->addWidget(checkBox1);
	mainLayout->addWidget(checkBox2);
	mainLayout->addWidget(checkBox3);
	mainLayout->addLayout(Box4);

	connect(bCancel,SIGNAL(clicked()),this,SLOT(slot_Close()));
	connect(bOk,SIGNAL(clicked()),this,SLOT(slot_Ok()));

}


FindWidget::~FindWidget()
{
}


void FindWidget::slot_Close()
{
	close();
}


void FindWidget::slot_Ok()
{

	//QWebPage::FindFlags findFlags;   //ooo
    QWebEnginePage::FindFlags findFlags;  //xx
	//findFlags = QWebPage.FindFlags();

	/*if ( checkBox1->isChecked() ) {						// Check search result for matching type.
		//findFlags |= QWebPage::HighlightAllOccurrences; //ooo
        findFlags |= QWebEnginePage::HighlightAllOccurrences; //xx
	}
	if ( checkBox2->isChecked() ) {
		//findFlags |= QWebPage::FindCaseSensitively; //ooo
        findFlags |= QWebEnginePage::FindCaseSensitively; //xx
	}
	if ( checkBox3->isChecked() ) {
		//findFlags |= QWebPage::FindBackward;    //ooo
        findFlags |= QWebEnginePage::FindBackward;    //xx
	}*/    //ooo

	Par2->findText(wordName->text(), findFlags);
	//close();
}

//#include "html_widget.moc"
