//=========================================================================
//  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 "smtk/session/rgg/plugin/smtkRGGAutoStart.h"

#include "smtk/session/rgg/plugin/smtkRGGSelectionBehavior.h"

#include "pqApplicationCore.h"
#include "pqObjectBuilder.h"

#include "vtkObjectFactory.h"
#include "vtkVersion.h"
#include "vtksys/SystemTools.hxx"

#include "smtk/extension/paraview/appcomponents/pqSMTKResourcePanel.h"
#include "smtk/view/json/jsonView.h"

#include "smtk/session/rgg/plugin/rggResourcePanelConfiguration_xml.h"

#include <QApplication>
#include <QMainWindow>
#include <QTimer>

static const QString selectionSyncStr = "smtk rgg selection sync";

namespace
{
void setView()
{
  for (QWidget* w : QApplication::topLevelWidgets())
  {
    QMainWindow* mainWindow = dynamic_cast<QMainWindow*>(w);
    if (mainWindow)
    {
      pqSMTKResourcePanel* dock = mainWindow->findChild<pqSMTKResourcePanel*>();
      // If the dock is not there, just try it again.
      if (dock)
      {
        nlohmann::json j = nlohmann::json::parse(rggResourcePanelConfiguration_xml);
        dock->setView(j[0]);
      }
      else
      {
        QTimer::singleShot(10, [](){
          setView();
        });
      }
    }
  }
}
}

smtkRGGAutoStart::smtkRGGAutoStart(QObject* parent) : Superclass(parent)
{
}

smtkRGGAutoStart::~smtkRGGAutoStart()
{
}

void smtkRGGAutoStart::startup()
{
  smtkRGGSelectionBehavior* selectionSync = smtkRGGSelectionBehavior::instance(this);

  auto pqCore = pqApplicationCore::instance();
  if (pqCore)
  {
    pqCore->registerManager(selectionSyncStr, selectionSync);
  }
  // Since the loading order of smtk plugins is indetermined, a spinning function call is used here
  // to set up the custom view.
  // TODO: A spinning call is not ideal, but it's a workaround for static initialization ordering problem.
  QTimer::singleShot(10, [](){
    setView();
  });
}

void smtkRGGAutoStart::shutdown()
{
  auto pqCore = pqApplicationCore::instance();
  if (pqCore)
  {
    pqCore->unRegisterManager(selectionSyncStr);
  }
}
