#include "stdafx.h"

#include "SetupManager.h"

#include "resource.h"

#include "xtr/ExteorOptions.h"
#include "xtr/ExtSourceManager.h"
#include "xtr/xtrServices.h"
#include "xtr/mfcMessageManager.h"

#include "xtr/core/PyTextProcessor.h"
#include "xtr/core/PyCore.h"

#include "ccl/lang/TextEnvironment.h"

namespace xtr {

using core::PyTextProcessor;
using cxxpython::PyCore;

void SetupManager::InitEnvironment() {
  Global::Instance().SetMessageManager(std::make_unique<mfcMessageManager>());
}

void SetupManager::CCLInitSequence() {
  InitSourceManager();
  InitTextModule();
}

void SetupManager::CCLExitSequence() {
  KillTextModule();
}

void SetupManager::InitSourceManager() {
  ccl::Environment::Instance().SetSourceManager(std::make_unique<ExtSourceManager>());
}

void SetupManager::InitTextModule() {
  static const std::string moduleName = "cctext";
  if (!LoadPython()) {
    return;
  } else {
    auto processor = std::make_unique<PyTextProcessor>();
    if (!PyCore::Instance().LoadModule(moduleName, moduleName)) {
      ::AfxMessageBox(IXTRS_PYERR_NOCORE, MB_ICONERROR);
    } else {
      processor->InitModule(moduleName);
    }
    ccl::lang::TextEnvironment::SetProcessor(std::move(processor));
  }
}

bool SetupManager::LoadPython() {
  if (!XTROptions::App().enablePython) {
    return false;
  }

  if (XTROptions::App().pyCrashed) {
    if (::AfxMessageBox(IXTRS_PYTHON_CRASH_PROMPT, MB_YESNO | MB_ICONQUESTION) != IDYES) {
      XTROptions::App().enablePython = FALSE;
      XTROptions::App().pyCrashed = FALSE;
      XTROptions::Get().Save();
      return false;
    }
  }

  XTROptions::App().pyCrashed = TRUE;
  XTROptions::Get().Save();

  if (!cxxpython::PyCore::Instance().Start(XTROptions::App().pythonPath)) {
    ::AfxMessageBox(IXTRS_PYERR_NOLOAD, MB_ICONERROR);
    return false;
  } else {
    XTROptions::App().pyCrashed = FALSE;
    XTROptions::Get().Save();
    return true;
  }
}

void SetupManager::KillTextModule() {
  cxxpython::PyCore::Instance().Stop();
}

} // namespace xtr