#include "stdafx.h"

#include "xtr/ui/UIHelper.h"

#include "resource.h"
#include "xtr/ExteorOptions.h"

namespace xtr::ui {

CRect WindowRect(const CWnd& wndCtrl) {
  CRect rect{};
  GetWindowRect(wndCtrl, &rect);
  return rect;
}

CRect ClientRect(const CWnd& wndCtrl) {
  CRect rect{};
  GetClientRect(wndCtrl, &rect);
  return rect;
}

CString WindowText(const CWnd& wndCtrl) {
  CString text{};
  wndCtrl.GetWindowTextW(text);
  return text;
}

CString TrimText(CString text) {
  text.Trim(L" -\n\r");
  return text;
}

CRect LocalCoordinatesFor(const CWnd& wndCtrl) {
  auto rect = WindowRect(wndCtrl);
  MapWindowPoints(HWND_DESKTOP, GetParent(wndCtrl), reinterpret_cast<LPPOINT>(&rect), 2);
  return rect;
}

TEXTMETRIC GlobalTextMetrics() {
  CDC pDC{};
  pDC.CreateCompatibleDC(nullptr);

  TEXTMETRIC metrics{};
  if (!pDC.GetTextMetricsW(&metrics)) {
    ::AfxMessageBox(IXTRE_TEXT_METRICS, MB_ICONERROR);
  }
  return metrics;
}

TEXTMETRIC TextMetricsOf(const CWnd& wndCtrl) {
  CDC pDC{};
  pDC.Attach(::GetDC(nullptr));
  pDC.SelectObject(wndCtrl.GetFont());

  TEXTMETRIC metrics{};
  if (!pDC.GetTextMetricsW(&metrics)) {
    ::AfxMessageBox(IXTRE_TEXT_METRICS, MB_ICONERROR);
  }
  return metrics;
}

void InitHeaderFor(CListCtrl& listCtr, const Header& header) {
  static constexpr auto autoWidth = -1;

  listCtr.DeleteAllItems();
  auto nCol = 0;
  for (const auto& column : header.columns) {
    listCtr.InsertColumn(
      nCol++,
      column.label,
      column.alignment,
      column.width.value_or(autoWidth));
  }
}

void InitReversedHeaderFor(CListCtrl& listCtr, const Header& header) {
  static constexpr auto autoWidth = -1;
  auto nCol = 0;
  for (auto iter = header.columns.rbegin(); iter != header.columns.rend(); ++iter) {
    listCtr.InsertColumn(
      ++nCol,
      iter->label,
      iter->alignment,
      iter->width.value_or(autoWidth));
  }
}

} // namespace xtr::ui