/***************************************************************************
 *   copyright       : (C) 2003-2024 by Pascal Brachet                     *
 *   https://www.xm1math.net/texmaker/                                     *
 *                                                                         *
 *   This program 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; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   @license GPL-2.0+ <https://spdx.org/licenses/GPL-2.0+.html>           *
 ***************************************************************************/
 
#include "browser.h"

#include <QtGui>
#include <QDebug>
#include <QPrinter>
#include <QMenuBar>
#include <QToolBar>
#include <QPushButton>
#include <QMenu>
#include <QDesktopServices>
#include <QUrl>
#include <QApplication>
#include <QScreen>
#include <QWindow>
#include <QGuiApplication>
#include <QWebEngineSettings>




#include "geticon.h"
#include "theme.h"

Browser::Browser( const QString home, bool showToolBar, QWidget* parent)
    : QMainWindow( parent)
{
isClosed=false;
setWindowTitle("Texmaker");
#if defined(Q_OS_MAC)
setWindowIcon(QIcon(":/datas/images/logo128.png"));
#else
setWindowIcon(getIcon(":/datas/images/appicon.png"));
#endif

#ifdef USB_VERSION
QSettings *config=new QSettings(QCoreApplication::applicationDirPath()+"/texmakerhtmlview.ini",QSettings::IniFormat); //for USB-stick version :
#else
QSettings *config=new QSettings(QSettings::IniFormat,QSettings::UserScope,"xm1","texmakerhtmlview");
#endif
config->beginGroup( "htmlviewer" );
#if (QT_VERSION >= QT_VERSION_CHECK(5, 14, 0))
   QRect screen = QWidget::screen()->geometry();
 #else
  QRect screen = (window() && window()->windowHandle() ? window()->windowHandle()->screen()->geometry() : QGuiApplication::primaryScreen()->geometry());
#endif
int w= config->value( "Geometries/MainwindowWidth",screen.width()/2).toInt();
int h= config->value( "Geometries/MainwindowHeight",screen.height()-150).toInt() ;
int x= config->value( "Geometries/MainwindowX",screen.width()/2).toInt();
int y= config->value( "Geometries/MainwindowY",30).toInt() ;

resize(w,h);
move(x,y);
windowstate=config->value("MainWindowState").toByteArray();
config->endGroup();

progress = 0;
view = new QWebEngineView(this);
view->page()->settings()->setAttribute(QWebEngineSettings::LocalContentCanAccessRemoteUrls,true);
if ( !home.isEmpty()) view->load(QUrl(home));
index=home;
ontop=false;

connect(view, SIGNAL(titleChanged(QString)), SLOT(adjustTitle()));
//connect(view, SIGNAL(loadProgress(int)), SLOT(setProgress(int)));
connect(view, SIGNAL(loadFinished(bool)), SLOT(finishLoading(bool)));


QMenu *fileMenu = menuBar()->addMenu(tr("&File"));
fileMenu->addAction(tr("Print"), this, SLOT(Print()));
fileMenu->addSeparator();
fileMenu->addAction(tr("Exit"), this, SLOT(close()));
if (showToolBar)
    {
    QToolBar *toolBar = addToolBar("Navigation");
    toolBar->setIconSize(QSize(22,22 ));
    toolBar->setStyleSheet(Theme::viewportLightStyleSheet);
    toolBar->setObjectName("Navigation");
    QAction *Act;
    Act = new QAction(getIcon(":/datas/images/home.png"), tr("Index"), this);
    connect(Act, SIGNAL(triggered()), this, SLOT(Index()));
    toolBar->addAction(Act);
    Act=view->pageAction(QWebEnginePage::Back);
    Act->setIcon(getIcon(":/datas/images/errorprev.png"));
    toolBar->addAction(Act);
    Act=view->pageAction(QWebEnginePage::Forward);
    Act->setIcon(getIcon(":/datas/images/errornext.png"));
    toolBar->addAction(Act);

    QWidget* spacer = new QWidget();
    spacer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    toolBar->addWidget(spacer);
    searchLineEdit = new QLineEdit(toolBar);
    searchLineEdit->setStyleSheet(Theme::lineeditStyleSheet);
    connect(searchLineEdit, SIGNAL(returnPressed()), this, SLOT(Find()));
    toolBar->addWidget(searchLineEdit);

    searchAct=new QAction(getIcon(":/datas/images/pdffind.png"), tr("Find"), this);
    toolBar->addAction(searchAct);
    connect(searchAct, SIGNAL(triggered()), this, SLOT(Find()));
    }
setCentralWidget(view);
setUnifiedTitleAndToolBarOnMac(true);
//if ( !home.isEmpty()) view->setUrl(QUrl(home));
restoreState(windowstate);
}

Browser::~Browser()
{

}

void Browser::closeEvent(QCloseEvent *e)
{
#ifdef USB_VERSION
QSettings config(QCoreApplication::applicationDirPath()+"/texmakerhtmlview.ini",QSettings::IniFormat); //for USB-stick version 
#else
QSettings config(QSettings::IniFormat,QSettings::UserScope,"xm1","texmakerhtmlview");
#endif
config.beginGroup( "htmlviewer" );
config.setValue("MainWindowState",saveState());
config.setValue("Geometries/MainwindowWidth", width() );
config.setValue("Geometries/MainwindowHeight", height() );
config.setValue("Geometries/MainwindowX", x() );
config.setValue("Geometries/MainwindowY", y() );
config.endGroup();
isClosed=true;
e->accept();
}

void Browser::adjustTitle()
{
if (progress <= 0 || progress >= 100)
    setWindowTitle(view->title());
else
    setWindowTitle(QString("%1 (%2%)").arg(view->title()).arg(progress));
}

void Browser::setProgress(int p)
{
progress = p;
adjustTitle();
}

void Browser::finishLoading(bool)
{
progress = 100;
adjustTitle();
if (ontop) view->page()->runJavaScript("window.location.href='#top';");
ontop=false;
}

void Browser::Index()
{
if ((view->url().toString(QUrl::RemoveFragment)!=index) && ( !index.isEmpty()))
  {
  ontop=true;
  view->load(QUrl(index));
  }
else view->page()->runJavaScript("window.location.href='#top';");
}

void Browser::Print()
{
pdffichier=QDir::homePath();
pdffichier="texmaker_page_temp_"+pdffichier.section('/',-1);
pdffichier=QString(QUrl::toPercentEncoding(pdffichier));
pdffichier.remove("%");
pdffichier=pdffichier+".pdf";
QString tempDir=QDir::tempPath();
pdffichier=tempDir+"/"+pdffichier;
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
view->page()->printToPdf(pdffichier);
#else
view->printToPdf(pdffichier);
#endif
QFileInfo fic(pdffichier);
if (fic.exists() && fic.isReadable() ) QDesktopServices::openUrl(QUrl("file://"+pdffichier));
}

void Browser::Find()
{
if (searchLineEdit->text().isEmpty()) return;
view->findText(searchLineEdit->text());
}
