#include <QGuiApplication>
#include <QScreen>
#include <QWidget>
#include <QMenuBar>
#include <QFileDialog>
#include <QUrl>
#include <QFileInfo>

#include <QDebug>

#include "MainWindow.hpp"


MainWindow::MainWindow ()
{
  createActions ();
  createMenus ();

  setWindowTitle (tr ("DSL - Draw Strength Line"));

  QScreen *screen = QGuiApplication::primaryScreen ();
  QRect screenGeometry = screen->geometry ();
  int screenWidth = screenGeometry.width () - 200;
  int screenHeight = screenGeometry.height () - 200;
  
  wa = new WorkArea (screenWidth, screenHeight, this);
  
  setCentralWidget (wa);

  setFixedSize (screenWidth, screenHeight);
}

void
MainWindow::open ()
{
  filename = QFileDialog::getOpenFileName (this,
						   QObject::
						   tr ("Open image file"),
						   QDir::currentPath (),
						   QObject::tr("Images files (*.jpg *.png);;All files (*.*)"));
  QDir::setCurrent(QString(filename).remove(QUrl(filename).fileName()));
  QString SLFilename = QFileDialog::getOpenFileName (this,
						     QObject::
						     tr ("Open strength lines file"),
						     QDir::currentPath (),
						     QObject::
						     tr
						     ("Json files (*.json);;All files (*.*)"));
  wa->loadImage (filename.toStdString ());
  wa->loadSL(SLFilename.toStdString());
  wa->setReadOnly(true);
  wa->repaint();
  setFixedSize (wa->geometry().width(), wa->geometry().height()+wa->geometry().y());
}

void
MainWindow::save ()
{
  QString fileToSave = QFileDialog::getSaveFileName (this,
						   QObject::tr ("Save file"),
						   QDir::currentPath ().append("/").append(QFileInfo(filename).baseName()).append(".json"),
						   QObject::tr("JSON file (*.json);;All files (*.*)"));
  if(!fileToSave.endsWith(".json"))
    fileToSave.append(".json");
  wa->saveStrengthLine (fileToSave.toStdString ());
}


void
MainWindow::createActions ()
{
  openAct = new QAction (tr ("&Open image"), this);
  openAct->setShortcuts (QKeySequence::Open);
  connect (openAct, &QAction::triggered, this, &MainWindow::open);

  saveAct = new QAction (tr ("&Save"), this);
  saveAct->setShortcuts (QKeySequence::Save);
  connect (saveAct, &QAction::triggered, this, &MainWindow::save);

  exitAct = new QAction (tr ("E&xit"), this);
  exitAct->setShortcuts (QKeySequence::Quit);
  connect (exitAct, &QAction::triggered, this, &QWidget::close);
}

void
MainWindow::createMenus ()
{
  fileMenu = menuBar ()->addMenu (tr ("&File"));
  fileMenu->addAction (openAct);
  fileMenu->addAction (saveAct);

  fileMenu->addSeparator ();

  fileMenu->addAction (exitAct);
}
