#include "mainwindow.h"
#include "ui_mainwindow.h"



MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    paintScene = QSharedPointer<PaintScene>(new PaintScene());
    ui->graphicsView->setScene(paintScene.data());

    setWindowTitle("MT_ImageToCoord");
}



MainWindow::~MainWindow()
{
    delete ui;
}



void MainWindow::on_saveButton_clicked()
{
    QString filename = QFileDialog::getSaveFileName(this, tr("Save source file"), QDir::currentPath(), tr("*.c") );
    QFile file(filename);
    file.open(QFile::WriteOnly | QFile::Truncate);
    QTextStream stream(&file);

    std::vector<QPointF> points = paintScene->getPoints();

    QStringList list = filename.split("/");
    QString name =  list.at(list.size() - 1);
    name.chop(2);

    QString arrayName = QString("%1Array").arg(name);
    QString structName = QString("%1Image").arg(name);

    stream << "/* Includes ------------------------------------------------------------------*/\n\n";
    stream << "#include \"paint.h\"\n\n\n\n";
    stream << "/* Declarations and definitions ----------------------------------------------*/\n\n";

    stream << "uint16_t ";
    stream << arrayName;
    stream << "[";
    stream << points.size() * 2;
    stream << "] = {\n";

    for (unsigned int i = 0; i < points.size(); i++)
    {
        stream << static_cast<int>(points.at(i).x());
        stream << ", ";
        stream << static_cast<int>(512 - points.at(i).y());

        if (i != (points.size() - 1))
        {
            stream << ", ";
        }

        if ((i != 0) && ((i % 10) == 0))
        {
            stream << "\n";
        }
    }

    stream << "};";
    stream << "\n\n";

    stream << "PAINT_Image ";
    stream << structName;
    stream << " = {\n   ";
    stream << points.size() * 2;
    stream << ",\n   ";
    stream << arrayName;
    stream << "\n};\n\n";

    file.close();
}



void MainWindow::on_clearButton_clicked()
{
    paintScene->clearScene();
}



void MainWindow::on_openButton_clicked()
{
    QString filename = QFileDialog::getOpenFileName(this, tr("Open image"), QDir::currentPath(), tr("*.png *.jpg *.bmp"));

    if (filename.isEmpty() == false)
    {
        QImage image;
        image.load(filename);
        paintScene->addImageItem(image);
    }
}
