#include "stdafx.h"

#include "xtr/dialog/PickOperation.h"

#include "resource.h"
#include "xtr/ui/HelpHandler.h"
#include "xtr/ExteorOptions.h"
#include "xtr/cclDescriptor.h"

namespace xtr::dialog {

#pragma warning( push )
#pragma warning( disable : 26440 26436 26454 )

BEGIN_MESSAGE_MAP(PickOperationDlg, CDialog)
  ON_COMMAND(IXTRC_XTR_HELP, &ThisClass::OpenHelp)

  ON_LBN_DBLCLK(IXTRC_OSS_SINT_DEF_LC, &CDialog::OnOK)
  ON_BN_CLICKED(IXTRC_OSS_RUN_AFTER_CLK_OK, &ThisClass::OnChange)
END_MESSAGE_MAP()

#pragma warning( pop )

PickOperationDlg::PickOperationDlg(ccl::oss::OSSchema& schema, 
                                   const ccl::oss::PictID pid, CWnd* pParent)
  : CDialog(IXTRD_OSS_OPERATIONS, pParent), oss{ schema }, activePID{ pid } {
  for (const auto opID : oss.Ops().VariantsFor(pid)) {
    operations.push_back(opID);
  }
  autorun = XTROptions::OSS().runOpAfterEdit;
}

void PickOperationDlg::DoDataExchange(CDataExchange* pDX) {
  CDialog::DoDataExchange(pDX);

  ::DDX_Control(pDX, IXTRC_OSS_SINT_DEF_LC, m_OperationList);

  ::DDX_Check(pDX, IXTRC_OSS_RUN_AFTER_CLK_OK, autorun);

  if (pDX->m_bSaveAndValidate)  {
    type = m_OperationList.GetCurSel();
    XTROptions::OSS().runOpAfterEdit = autorun;
  }
}

BOOL PickOperationDlg::OnInitDialog() {
  CDialog::OnInitDialog();
  for (auto& iter : operations) {
    m_OperationList.AddString(info::Label(iter));
  }
  m_OperationList.SetCurSel(Operation2ID(oss.Ops()(activePID)->type));
  return TRUE;
}

void PickOperationDlg::OnChange() { // NOLINT(readability-convert-member-functions-to-static)
  UpdateData(TRUE);
}

void PickOperationDlg::OpenHelp() { // NOLINT(readability-convert-member-functions-to-static)
  ui::HelpHandler::RunHelp(ui::HelpID::operations);
}

ccl::ops::Type PickOperationDlg::ID2Operation(int32_t selectedID) const {
  if (selectedID < 0 || selectedID >= ssize(operations)) {
    return ccl::ops::Type::tba;
  } else {
    return operations.at(selectedID);
  }
}

int32_t PickOperationDlg::Operation2ID(ccl::ops::Type operationType) const noexcept {
  auto i = 0;
  for (const auto operation : operations) {
    if (operationType == operation) {
      return i;
    } else {
      ++i;
    }
  }
  return -1;
}

} // namespace xtr::dialog