//=========================================================================
//  Copyright (c) Kitware, Inc.
//  All rights reserved.
//  See LICENSE.txt for details.
//
//  This software is distributed WITHOUT ANY WARRANTY; without even
//  the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
//  PURPOSE.  See the above copyright notice for more information.
//=========================================================================

#include "pqACE3PRecentProjectsMenu.h"

#include "pqACE3PProjectLoader.h"

#include "pqApplicationCore.h"
#include "pqInterfaceTracker.h"
#include "pqRecentlyUsedResourcesList.h"
#include "pqServer.h"
#include "pqServerConfiguration.h"
#include "pqServerResource.h"
#include "pqWaitCursor.h"

#include <QAction>
#include <QDebug>
#include <QList>
#include <QMap>
#include <QMenu>
#include <QString>

//=============================================================================
pqACE3PRecentProjectsMenu::pqACE3PRecentProjectsMenu(QMenu* menu, QObject* p)
  : QObject(p)
  , m_menu(menu)
{
  QObject::connect(m_menu, &QMenu::aboutToShow, this, &pqACE3PRecentProjectsMenu::buildMenu);
  QObject::connect(m_menu, &QMenu::triggered, this, &pqACE3PRecentProjectsMenu::onOpenProject);
}

//-----------------------------------------------------------------------------
pqACE3PRecentProjectsMenu::~pqACE3PRecentProjectsMenu() {}

//-----------------------------------------------------------------------------
void pqACE3PRecentProjectsMenu::buildMenu()
{
  if (!m_menu)
  {
    return;
  }

  m_menu->clear();
  auto loader = pqACE3PProjectLoader::instance();

  // Get the set of all resources in most-recently-used order ...
  const pqRecentlyUsedResourcesList::ListT& resources =
    pqApplicationCore::instance()->recentlyUsedResources().list();
  for (int cc = 0; cc < resources.size(); cc++)
  {
    // Filter out resources not marked by our extension
    const pqServerResource& resource = resources[cc];
    if (!loader->canLoad(resource))
    {
      continue;
    }

    // Filter out anything from a remote server
    pqServerConfiguration config = resource.configuration();
    if (!config.isNameDefault())
    {
      continue;
    }

    // Add submenu item
    QString label = resource.toURI();
    if (label.startsWith("builtin:"))
    {
      label = label.mid(8);
    }
    QAction* const act = new QAction(label, m_menu);
    act->setData(resource.serializeString());
    m_menu->addAction(act);
  }
}

//-----------------------------------------------------------------------------
void pqACE3PRecentProjectsMenu::onOpenProject(QAction* action)
{
  QString data = action ? action->data().toString() : QString();
  if (!data.isEmpty())
  {
    pqServerResource resource(action->data().toString());
    pqWaitCursor cursor;
    pqACE3PProjectLoader::instance()->load(resource);
  }
}
