/***************************************************************************
 *   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 "algowebpage.h"


#include <QMessageBox>
#include <QInputDialog>
#include <QDebug>



AlgoWebPage::AlgoWebPage(QObject* parent, AlgoConsole* cons):QWebEnginePage(parent)
{
result=false;
stop=false;
QObject::connect(&timer, SIGNAL(timeout()), &loop_aff, SLOT(quit()));
console=cons;
view=qobject_cast<AlgoWebView *>(parent);
}

AlgoWebPage::~AlgoWebPage(){
loop_pause.quit();
loop_aff.quit();
timer.disconnect();
stop=true;
}

void AlgoWebPage::javaScriptAlert(const QUrl &securityOrigin, const QString& msg)
{
    if (!stop) QMessageBox::information(view,"AlgoBox", msg, QMessageBox::Ok);
}

bool AlgoWebPage::javaScriptPrompt(const QUrl &securityOrigin, const QString& msg, const QString& defaultValue, QString* result)
{
if (stop) return true;
//    bool ok = false;
    QStringList msglist=msg.split("\n");
    console->output(msglist.at(0));
    QEventLoop loop;

QObject::connect(console, SIGNAL(done()), &loop, SLOT(quit()));
loop.exec();

    *result=console->answer;
    if (result) return true;
    else return false;
//     QString texte="<b><span style=\"font-size:13pt;\">"+msglist.at(0)+"</span></b>";
//     if (msglist.count()==3) texte+="<br><i>"+msglist.at(1)+"<br>"+msglist.at(2)+"</i>";
//     QString x = QInputDialog::getText(this->view(), "AlgoBox", texte , QLineEdit::Normal, defaultValue, &ok);
//     if (ok && result) {
//         *result = x;
//     }
//    return ok;
}

bool AlgoWebPage::javaScriptConfirm(const QUrl &securityOrigin, const QString& msg)
{
if (stop) return true;
if (msg=="Pause")
  {
  loop_pause.exec();
  return result;
  }
else return QMessageBox::Yes == QMessageBox::information(view,"AlgoBox", msg, QMessageBox::Yes, QMessageBox::No);
}

bool AlgoWebPage::shouldInterruptJavaScript()
{
return false;
}

void AlgoWebPage::continuer()
{
result=true;
loop_pause.quit();
}

void AlgoWebPage::arreter()
{
result=false;
loop_pause.quit();
}

void AlgoWebPage::stopaffichage()
{
stop=true;
}

void AlgoWebPage::minipause()
{
loop_aff.quit();  
if (stop) {timer.disconnect();return;}
timer.setSingleShot(true);
timer.start(10);
loop_aff.exec();
}

