//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      GUI/View/Canvas/SavePlotAssistant.cpp
//! @brief     Implements class SavePlotAssistant.
//!
//! @homepage  http://www.bornagainproject.org
//! @license   GNU General Public License v3 or higher (see COPYING)
//! @copyright Forschungszentrum Jülich GmbH 2018
//! @authors   Scientific Computing Group at MLZ (see CITATION, AUTHORS)
//
//  ************************************************************************************************

#include "GUI/View/Canvas/SavePlotAssistant.h"
#include "Base/Util/Assert.h"
#include "Device/IO/IOFactory.h"
#include "GUI/View/Plotter/ColorMap.h"
#include "GUI/View/Widget/AppConfig.h"
#include "GUI/View/Widget/FileDialog.h"
#include <QFile>
#include <QMessageBox>
#include <QVector>
#include <qcustomplot.h>
#include <utility>

namespace {

const QString png_extension = ".png";
const QString jpg_extension = ".jpg";
const QString pdf_extension = ".pdf";
const QString int_extension = ".int";
const QString tif_extension = ".tif";
const QString txt_extension = ".txt";

class Format {
public:
    Format() = default;
    Format(QString file_extention, QString filter);
    QString m_file_extention;
    QString m_filter;
};

Format::Format(QString file_extention, QString filter)
    : m_file_extention(std::move(file_extention))
    , m_filter(std::move(filter))
{
}

const QVector<Format> outFormats = {
    Format(png_extension, "png Image (*.png)"),
    Format(jpg_extension, "jpg Image (*.jpg)"),
    Format(pdf_extension, "pdf File (*.pdf)"),
    Format(int_extension, "BornAgain ASCII format (*.int)"),
    Format(txt_extension, "Simple ASCII table (*.txt)"),
#ifdef BA_TIFF_SUPPORT
    Format(tif_extension, "32-bits TIFF files (*.tif)"),
#endif
};

bool isPngFile(const QString& fname)
{
    return fname.endsWith(png_extension, Qt::CaseInsensitive);
}

bool isJpgFile(const QString& fname)
{
    return fname.endsWith(jpg_extension, Qt::CaseInsensitive);
}

bool isPdfFile(const QString& fname)
{
    return fname.endsWith(pdf_extension, Qt::CaseInsensitive);
}

void saveToFile(const QString& fname, QCustomPlot* plot, const Datafield* output_data)
{
    if (isPngFile(fname))
        plot->savePng(fname);

    else if (isJpgFile(fname))
        plot->saveJpg(fname);

    else if (isPdfFile(fname))
        plot->savePdf(fname, plot->width(), plot->height());

    else {
        ASSERT(output_data);
        IO::writeDatafield(*output_data, fname.toStdString());
    }
}

/*
//! Returns string contraining all defined filters in the format suitable for QFileDialog
QString getFilterString()
{
    QString result;
    for (int i = 0; i < outFormats.size(); ++i) {
        result.append(outFormats[i].m_filter);
        if (i != outFormats.size() - 1)
            result.append(";;");
    }
    return result;
}

bool isValidExtension(const QString& fname)
{
    for (const auto& outFormat : outFormats)
        if (fname.endsWith(outFormat.m_file_extention, Qt::CaseInsensitive))
            return true;
    return false;
}

QString getExtensionFromFilterName(const QString& filterName)
{
    for (const auto& outFormat : outFormats)
        if (outFormat.m_filter == filterName)
            return outFormat.m_file_extention;
    return "";
}

//! Compose file name to save plot from information provided by QFileDialog
QString composeFileName(const QString& fname, const QString& filterName)
{
    if (fname.isEmpty() || filterName.isEmpty())
        return "";
    if (isValidExtension(fname))
        return fname;
    return fname + getExtensionFromFilterName(filterName);
}
*/
} // namespace


void GUI::Plot::savePlot(QCustomPlot* plot, const Datafield* output_data)
{
    static const QString defaultExtension = ".png";
    QString fname =
        GUI::FileDialog::w1_1f("Save Plot", gApp->artifact_export_dir, "*" + defaultExtension);
    if (fname.isEmpty())
        return;
    if (!fname.endsWith(defaultExtension))
        fname += defaultExtension;

    try {
        ::saveToFile(fname, plot, output_data);
    } catch (const std::exception& ex) {
        QMessageBox::warning(nullptr, "Cannot save", "Cannot save picture in file " + fname);
    }
}
