/***************************************************************************
 *   copyright       : (C) 2009-2022 by Pascal Brachet                     *
 *   https://www.xm1math.net/algobox/                                       *
 *                                                                         *
 *   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 "algowebview.h"


#include <QContextMenuEvent>
#include <QMenu>
#include <QAction>
#include <QFileDialog>
#include <QDir>
#include <QDesktopServices>
#include <QUrl>
#include <QTimer>
#include <QDebug>



AlgoWebView::AlgoWebView(QWidget *parent)
    : QWebEngineView(parent)
{
pdffichier=QDir::homePath();
pdffichier="algobox_temp_"+pdffichier.section('/',-1);
pdffichier=QString(QUrl::toPercentEncoding(pdffichier));
pdffichier.remove("%");
pdffichier=pdffichier+".pdf";
QString tempDir=QDir::tempPath();
pdffichier=tempDir+"/"+pdffichier;
connect(this,SIGNAL(loadFinished(bool)), SLOT(finishLoading(bool)));
file_watcher = new QFileSystemWatcher();
connect(file_watcher, SIGNAL(fileChanged(QString)), this, SLOT(voirPdf(QString)));
}
AlgoWebView::~AlgoWebView()
{

}
void AlgoWebView::contextMenuEvent(QContextMenuEvent *event)
{
QMenu *menu = new QMenu(this);
menu->addAction(QString::fromUtf8("Imprimer (pdf)"), this, SLOT(exporterPdf()));  
menu->exec(mapToGlobal(event->pos()));
delete menu;
}

void AlgoWebView::finishLoading(bool)
{
page()->printToPdf(pdffichier);
}


void AlgoWebView::exporterPdf()
{
page()->printToPdf(pdffichier);
file_watcher->addPath(pdffichier);
}

void AlgoWebView::voirPdf(QString)
{
file_watcher->removePath(pdffichier);
QFileInfo fic(pdffichier);
if (fic.exists() && fic.isReadable() ) QDesktopServices::openUrl(QUrl("file:///"+pdffichier));
}
