/* Copyright (C) 2024 Marco Scarpetta
 *
 * This file is part of PDF Mix Tool.
 *
 * PDF Mix Tool 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.
 *
 * PDF Mix Tool 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 PDF Mix Tool. If not, see <http://www.gnu.org/licenses/>.
 */

#include "crop.h"

#include <fstream>
#include <QBoxLayout>
#include <QLabel>

Crop::Crop(QWidget *parent) :
    AbstractOperation(parent),
    m_output_preview{new OutputPreview{this}},
    m_pages_selector{new PagesSelector{true, true, this}}
{
    m_name = tr("Crop");
    m_icon = ":/icons/crop.svg";

    QVBoxLayout *v_layout = new QVBoxLayout{};
    this->setLayout(v_layout);

    QHBoxLayout *h_layout = new QHBoxLayout{};

    QGridLayout *grid_layout = new QGridLayout{};
    h_layout->addLayout(grid_layout);

    int r{0};
    QLabel *label = new QLabel{tr("Keep aspect ratio:"), this};
    grid_layout->addWidget(label, r, 0);
    grid_layout->addWidget(&m_keep_aspect_ratio, r++, 1);

    QWidget *spacer = new QWidget(this);
    spacer->setMinimumHeight(20);
    grid_layout->addWidget(spacer, r++, 0, 1, 2);
    label = new QLabel{QString("<b>") + tr("Crop margins") + "</b>", this};
    grid_layout->addWidget(label, r++, 0, 1, 2);
    spacer->setMinimumHeight(10);
    grid_layout->addWidget(spacer, r++, 0, 1, 2);

    label = new QLabel{tr("Left:"), this};
    grid_layout->addWidget(label, r, 0);
    m_left.setSuffix(" cm");
    m_left.setDecimals(1);
    m_left.setSingleStep(0.1);
    m_left.setMaximum(1000.0);
    grid_layout->addWidget(&m_left, r++, 1);

    label = new QLabel{tr("Top:"), this};
    grid_layout->addWidget(label, r, 0);
    m_top.setSuffix(" cm");
    m_top.setDecimals(1);
    m_top.setSingleStep(0.1);
    m_top.setMaximum(1000.0);
    grid_layout->addWidget(&m_top, r++, 1);

    label = new QLabel{tr("Right:"), this};
    grid_layout->addWidget(label, r, 0);
    m_right.setSuffix(" cm");
    m_right.setDecimals(1);
    m_right.setSingleStep(0.1);
    m_right.setMaximum(1000.0);
    grid_layout->addWidget(&m_right, r++, 1);

    label = new QLabel{tr("Bottom:"), this};
    grid_layout->addWidget(label, r, 0);
    m_bottom.setSuffix(" cm");
    m_bottom.setDecimals(1);
    m_bottom.setSingleStep(0.1);
    m_bottom.setMaximum(1000.0);
    grid_layout->addWidget(&m_bottom, r++, 1);

    spacer->setMinimumHeight(20);
    grid_layout->addWidget(spacer, r++, 0, 1, 2);
    label = new QLabel{QString("<b>") + tr("Page size") + "</b>", this};
    label->setContentsMargins(0, 20, 0, 10);
    grid_layout->addWidget(label, r++, 0, 1, 2);
    spacer->setMinimumHeight(10);
    grid_layout->addWidget(spacer, r++, 0, 1, 2);

    label = new QLabel{tr("Width:"), this};
    grid_layout->addWidget(label, r, 0);
    m_width.setSuffix(" cm");
    m_width.setDecimals(1);
    m_width.setSingleStep(0.1);
    grid_layout->addWidget(&m_width, r++, 1);

    label = new QLabel{tr("Height:"), this};
    grid_layout->addWidget(label, r, 0);
    m_height.setSuffix(" cm");
    m_height.setDecimals(1);
    m_height.setSingleStep(0.1);
    grid_layout->addWidget(&m_height, r++, 1);

    grid_layout->addWidget(new QWidget(this), r, 0, 1, 2);
    grid_layout->setRowStretch(r++, 1);

    m_output_preview->setMinimumHeight(100);
    h_layout->addWidget(m_output_preview, 10);

    QVBoxLayout *arrows_layout = new QVBoxLayout();
    arrows_layout->addWidget(new QWidget{this});
    QPushButton *prev_page = new QPushButton{this};
    prev_page->setIcon(QIcon::fromTheme("go-previous"));
    prev_page->setFixedSize(60, 60);
    prev_page->setIconSize(QSize(50, 50));
    prev_page->setShortcut(Qt::Key_Left);
    arrows_layout->addWidget(prev_page);
    QPushButton *next_page = new QPushButton{this};
    next_page->setIcon(QIcon::fromTheme("go-next"));
    next_page->setFixedSize(60, 60);
    next_page->setIconSize(QSize(50, 50));
    next_page->setShortcut(Qt::Key_Right);
    arrows_layout->addWidget(next_page);
    arrows_layout->addWidget(new QWidget{this});
    arrows_layout->setStretch(0, 1);
    arrows_layout->setStretch(3, 1);

    h_layout->addLayout(arrows_layout);

    h_layout->setStretch(1, 1);

    v_layout->addLayout(h_layout);

    v_layout->addWidget(m_pages_selector);

    h_layout = new QHBoxLayout();
    v_layout->addLayout(h_layout);

    // spacer
    h_layout->addWidget(new QWidget(this), 1);

    QPushButton *save_as_button = new QPushButton(
        QIcon::fromTheme("document-save-as"),
        tr("Save as…"),
        this);
    save_as_button->setShortcut(QKeySequence::SaveAs);
    save_as_button->setToolTip(
        QString(TOOLTIP_STRING)
            .arg(
                save_as_button->text(),
                save_as_button->shortcut().toString()));

    h_layout->addWidget(&m_save_button);
    h_layout->addWidget(save_as_button);

    connect(&m_keep_aspect_ratio, &QCheckBox::clicked,
            this, &Crop::keep_aspect_ratio_changed);
    connect(&m_top, &DoubleSpinBox::valueChangedByUser,
            this, &Crop::top_changed);
    connect(&m_bottom, &DoubleSpinBox::valueChangedByUser,
            this, &Crop::bottom_changed);
    connect(&m_left, &DoubleSpinBox::valueChangedByUser,
            this, &Crop::left_changed);
    connect(&m_right, &DoubleSpinBox::valueChangedByUser,
            this, &Crop::right_changed);
    connect(&m_width, &DoubleSpinBox::valueChangedByUser,
            this, &Crop::width_changed);
    connect(&m_height, &DoubleSpinBox::valueChangedByUser,
            this, &Crop::height_changed);
    connect(prev_page, &QPushButton::clicked,
            this, &Crop::prev_page);
    connect(next_page, &QPushButton::clicked,
            this, &Crop::next_page);

    connect(&m_save_button, &QPushButton::pressed,
            [=]() {save(false);});
    connect(save_as_button, &QPushButton::pressed,
            [=]() {save(true);});
}

void Crop::set_pdf_info(const PdfInfo &pdf_info)
{
    m_w_over_h = pdf_info.width() / pdf_info.height();

    m_pages_selector->set_num_pages(pdf_info.n_pages());
    AbstractOperation::set_pdf_info(pdf_info);
    m_output_preview->set_pdf_info(m_pdf_info);

    set_spinbox_maximum();

    adjust_page_size();

    m_output_preview->show_crop(m_top.value(), m_bottom.value(),
                                m_left.value(), m_right.value());
}

void Crop::keep_aspect_ratio_changed(bool checked)
{
    if (checked)
    {
        double w = m_pdf_info.width() - m_left.value() - m_right.value();
        double h = m_pdf_info.height() - m_top.value() - m_bottom.value();

        double r = std::min(w / m_pdf_info.width(), h / m_pdf_info.height());

        m_width.setValueByCode(r * m_pdf_info.width());
        m_height.setValueByCode(r * m_pdf_info.height());

        m_right.setValueByCode(
            m_pdf_info.width() - m_width.value() - m_left.value());
        m_bottom.setValueByCode(
            m_pdf_info.height() - m_height.value() - m_top.value());

        m_output_preview->show_crop(m_top.value(), m_bottom.value(),
                                    m_left.value(), m_right.value());
    }

    set_spinbox_maximum();
}

void Crop::left_changed(double value)
{
    if (m_keep_aspect_ratio.isChecked())
    {
        m_right.setValueByCode(
            m_pdf_info.width() - value - m_width.value());
    }
    else
    {
        adjust_page_size();
    }

    set_spinbox_maximum();

    m_output_preview->show_crop(m_top.value(), m_bottom.value(),
                                m_left.value(), m_right.value());
}

void Crop::top_changed(double value)
{
    if (m_keep_aspect_ratio.checkState())
    {
        m_bottom.setValueByCode(
            m_pdf_info.height() - value - m_height.value());
    }
    else
    {
        adjust_page_size();
    }

    set_spinbox_maximum();

    m_output_preview->show_crop(m_top.value(), m_bottom.value(),
                                m_left.value(), m_right.value());
}

void Crop::right_changed(double value)
{
    if (m_keep_aspect_ratio.checkState())
    {
        m_left.setValueByCode(
            m_pdf_info.width() - value - m_width.value());
    }
    else
    {
        adjust_page_size();
    }

    set_spinbox_maximum();

    m_output_preview->show_crop(m_top.value(), m_bottom.value(),
                                m_left.value(), m_right.value());
}

void Crop::bottom_changed(double value)
{
    if (m_keep_aspect_ratio.checkState())
    {
        m_top.setValueByCode(
            m_pdf_info.height() - value - m_height.value());
    }
    else
    {
        adjust_page_size();
    }

    set_spinbox_maximum();

    m_output_preview->show_crop(m_top.value(), m_bottom.value(),
                                m_left.value(), m_right.value());
}

void Crop::width_changed(double value)
{
    m_right.setValueByCode(m_pdf_info.width() -
                           m_width.value() - m_left.value());

    if (m_keep_aspect_ratio.isChecked())
    {
        double h = value / m_w_over_h;

        m_height.setValueByCode(h);
        m_bottom.setValueByCode(m_pdf_info.height() - h - m_top.value());
    }
    else
    {
        m_left.setMaximum(m_pdf_info.width() - m_right.value());
    }

    set_spinbox_maximum();

    m_output_preview->show_crop(m_top.value(), m_bottom.value(),
                                m_left.value(), m_right.value());
}

void Crop::height_changed(double value)
{
    m_bottom.setValueByCode(m_pdf_info.height() -
                            m_height.value() - m_top.value());

    if (m_keep_aspect_ratio.isChecked())
    {
        double w = m_w_over_h * value;

        m_width.setValueByCode(w);
        m_right.setValueByCode(m_pdf_info.width() - w - m_left.value());
    }
    else
    {
        m_top.setMaximum(m_pdf_info.height() - m_bottom.value());
    }

    set_spinbox_maximum();

    m_output_preview->show_crop(m_top.value(), m_bottom.value(),
                                m_left.value(), m_right.value());
}

void Crop::adjust_page_size()
{
    m_width.setValueByCode(
        m_pdf_info.width() - m_left.value() - m_right.value());
    m_height.setValueByCode(
        m_pdf_info.height() - m_top.value() - m_bottom.value());
}

void Crop::set_spinbox_maximum()
{
    if (m_keep_aspect_ratio.isChecked())
    {
        double max_w = m_pdf_info.width() - m_left.value();
        double max_h = m_pdf_info.height() - m_top.value();

        double r = std::min(max_w / m_pdf_info.width(),
                            max_h / m_pdf_info.height());

        m_width.setMaximum(r * m_pdf_info.width());
        m_height.setMaximum(r * m_pdf_info.height());

        m_left.setMaximum(m_pdf_info.width() - m_width.value());
        m_top.setMaximum(m_pdf_info.height() - m_height.value());
        m_right.setMaximum(m_pdf_info.width() - m_width.value());
        m_bottom.setMaximum(m_pdf_info.height() - m_height.value());
    }
    else
    {
        m_width.setMaximum(m_pdf_info.width() - m_left.value());
        m_height.setMaximum(m_pdf_info.height() - m_top.value());

        m_left.setMaximum(m_pdf_info.width() - m_right.value());
        m_top.setMaximum(m_pdf_info.height() - m_bottom.value());
        m_right.setMaximum(m_pdf_info.width() - m_left.value());
        m_bottom.setMaximum(m_pdf_info.height() - m_top.value());
    }
}

void Crop::prev_page()
{
    m_output_preview->set_first_page(m_output_preview->first_page() - 1);
}

void Crop::next_page()
{
    m_output_preview->set_first_page(m_output_preview->first_page() + 1);
}

int Crop::output_pages_count()
{
    return m_pdf_info.n_pages();
}

void Crop::save(bool save_as)
{
    if (m_pages_selector->has_error())
        return;

    std::vector<std::pair<int, int>> rotate_intervals =
        m_pages_selector->get_selected_intervals();

    if (save_as)
    {
        if (!show_save_as_dialog())
            return;
    }
    else
    {
        if (!show_overwrite_dialog())
            return;
    }

    emit write_started();

    try
    {
        std::locale old_locale{std::locale::global(std::locale::classic())};

        QPDF qpdf;
        qpdf.processFile(m_pdf_info.filename().c_str());

        std::vector<bool> crop_pages(m_pdf_info.n_pages(), false);

        std::vector<std::pair<int, int>>::iterator it;
        for (it = rotate_intervals.begin(); it != rotate_intervals.end(); ++it)
            for (int i = it->first; i <= it->second; i++)
                crop_pages[i] = true;

        emit progress_changed(20);

        // Iterate through all pages
        int i = -1;
        for (const QPDFObjectHandle &page : qpdf.getAllPages())
        {
            if (!crop_pages[++i])
                continue;

            QPDFPageObjectHelper page_helper(page);
            QPDFObjectHandle media_box = page_helper.getMediaBox();
            QPDFObjectHandle crop_box = page_helper.getCropBox();

            // If crop box is not defined, use media box
            if (crop_box.isNull())
            {
                crop_box = media_box;
            }

            // Define new crop box boundaries
            double media_left = media_box.getArrayItem(0).getNumericValue();
            double media_bottom = media_box.getArrayItem(1).getNumericValue();
            double media_right = media_box.getArrayItem(2).getNumericValue();
            double media_top = media_box.getArrayItem(3).getNumericValue();

            double new_left = media_left + m_left.value() * cm;
            double new_bottom = media_bottom + m_bottom.value() * cm;
            double new_right = media_right - m_right.value() * cm;
            double new_top = media_top - m_top.value() * cm;

            // Set the new crop box
            crop_box.setArrayItem(0, QPDFObjectHandle::newReal(new_left));
            crop_box.setArrayItem(1, QPDFObjectHandle::newReal(new_bottom));
            crop_box.setArrayItem(2, QPDFObjectHandle::newReal(new_right));
            crop_box.setArrayItem(3, QPDFObjectHandle::newReal(new_top));

            // Update the crop box in the page dictionary
            page_helper.getObjectHandle().replaceKey("/CropBox", crop_box);
        }

        QPDFWriter writer(qpdf);
        writer.setOutputMemory();
        writer.write();
        Buffer *buffer = writer.getBuffer();

        const char *buf = reinterpret_cast<const char *>(buffer->getBuffer());

        emit progress_changed(70);

        // write the PDF file to disk
        std::ofstream output_file_stream;
        output_file_stream.open(m_save_filename.toStdString());
        output_file_stream.write(buf, buffer->getSize());
        output_file_stream.close();
        delete buffer;

        std::locale::global(old_locale);

        emit write_finished(m_save_filename);
    }
    catch (std::exception &e)
    {
        emit write_error(QString::fromStdString(e.what()));
    }

}
