/***
   This file is part of fly-ocr.

   Copyright (C) 2021 LLC "RusBITech-Astra" (https://astralinux.ru)

   Foobar 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 3 of the License, or
   (at your option) any later version.

   Foobar 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 fly-ocr. If not, see <https://www.gnu.org/licenses/>.
***/

#include <QWebEngineView>
#include <QDomDocument>
#include <fly-ocr/ocrengine.h>
#include "hocrdocument.h"
#include "outputviewerhtml.h"
#include "recognizer.h"
#include "sourcemanager.h"
#include "utils.h"

OutputViewerHtml::OutputViewerHtml(QWidget* parent) : OutputEditor(parent)
{
    m_browser = new QWebEngineView(this);

    QHBoxLayout* layout = new QHBoxLayout();
    layout->addWidget(m_browser);
    setLayout(layout);
}

OutputViewerHtml::~OutputViewerHtml()
{}

void OutputViewerHtml::read(int pageNumber, const SourceDocumentPage* page)
{
    if (engine()) {
        QByteArray data = engine()->getPageData(pageNumber, OcrEngineFactory::HTML);
        if (!data.isEmpty())
            m_browser->setHtml(QString::fromUtf8(data));
        else {
            data = engine()->getPageData(pageNumber, OcrEngineFactory::HOCR);
            HOCRDocument document;
            QDomDocument doc;
            doc.setContent(QString::fromUtf8(data));
            QDomElement pageDiv = doc.firstChildElement("div");
            QMap<QString, QString> attrs = HOCRItem::deserializeAttrGroup(pageDiv.attribute("title"));
            attrs["image"] = QString("'%1'").arg(page->path);
            attrs["ppageno"] = QString::number(page->page);
            attrs["rot"] = QString::number(page->angle);
            attrs["res"] = QString::number(page->resolution);
            pageDiv.setAttribute("title", HOCRItem::serializeAttrGroup(attrs));
            document.insertPage(document.pageCount(), pageDiv, true);
            m_browser->setHtml(document.toHTML());
        }
    }
}

bool OutputViewerHtml::isModified() const
{
    return false;
}

void OutputViewerHtml::commit()
{}

void OutputViewerHtml::clear()
{
    m_browser->setUrl(QUrl());
}

void OutputViewerHtml::setLanguage(const QString& lang)
{
    Q_UNUSED(lang);
}
