#include "tycho.h"

static
ProjectModel *makeModel(Project *proj)
{
   switch(proj->getType()) {
      case ProjectType::Map: return new MapModel(proj);
   }
}

static
ProjectView *makeView(Project *proj)
{
   switch(proj->getType()) {
      case ProjectType::Map: return new MapView(proj);
   }
}

Project::Project(ProjectType _type) :
   QMdiSubWindow(),
   type(_type),
   model(makeModel(this)),
   view(makeView(this))
{
   auto widget = new QWidget(this);

   setupUi(widget);

   setWidget(widget);
   setAttribute(Qt::WA_DeleteOnClose);

   listView->setModel(dynamic_cast<QAbstractItemModel *>(model));
   verticalLayout->insertWidget(0, dynamic_cast<QWidget *>(view));

   connect(listView,
           SIGNAL(doubleClicked(QModelIndex const &)),
           dynamic_cast<QObject *>(model),
           SLOT(select(QModelIndex const &)));

   dbgPrintFunc();
}

Project::~Project()
{
   dbgPrintFunc();
}

ProjectType Project::getType() const
{
   return type;
}

ProjectModel *Project::getModel() const
{
   return model;
}

MapModel *Project::getMapModel() const
{
   return dynamic_cast<MapModel *>(model);
}

void Project::closeEvent(QCloseEvent *event)
{
   if(model->isDirty()) {
      QMessageBox msg;
      msg.setText(tr("Do you want to save your changes to this project before closing it?"));
      msg.setInformativeText(tr("Unsaved changes will be lost unless you save."));
      msg.setStandardButtons(QMessageBox::Save |
                             QMessageBox::Discard |
                             QMessageBox::Cancel);
      msg.setDefaultButton(QMessageBox::Save);

      switch(msg.exec()) {
         case QMessageBox::Save:
            model->save();
            break;
         case QMessageBox::Discard:
            break;
         case QMessageBox::Cancel:
            event->ignore();
            return;
         default:
            Q_UNREACHABLE();
      }
   }

   event->accept();
}

// EOF
