#include "stdafx.h"

#include "xtr/ui/RSListCtrl.h"

#include "xtr/Exteor.h"

namespace xtr::ui {

int32_t RSListCtrl::GetColumnCount() const {
  const auto* pHeader = GetHeaderCtrl();
  return pHeader == nullptr ? 0 : pHeader->GetItemCount();
}

int32_t RSListCtrl::GetFocusIndex() const {
  return GetNextItem(mfc::noItems, LVIS_FOCUSED);
}

int32_t RSListCtrl::GetSelectedIndex() const {
  return GetNextItem(mfc::noItems, LVIS_SELECTED);
}

void RSListCtrl::SetSelection(const int32_t nIndex) {
  if (nIndex < GetItemCount()) {
    SetItemState(nIndex, LVIS_SELECTED|LVIS_FOCUSED, LVIS_SELECTED|LVIS_FOCUSED);
  }
}

void RSListCtrl::ClearSelection() {
  SetItemState(mfc::noItems, 0, LVIS_DROPHILITED | LVIS_SELECTED | LVIS_FOCUSED);
}

void RSListCtrl::MoveSelectedItemsTo(RSListCtrl& dest, const int32_t coloumns) {
  if (coloumns != 0) {
    dest.SetItemState(mfc::noItems, 0, LVIS_SELECTED | LVIS_FOCUSED);
    auto item{ mfc::noItems };
    while ((item = GetNextItem(mfc::noItems, LVNI_SELECTED)) != mfc::noItems) {
      const auto line = dest.GetItemCount();
      dest.InsertItem(line, GetItemText(item, 0));
      dest.SetItemState(line, LVIS_SELECTED, LVIS_SELECTED);
      for (auto i = 1; i < coloumns; ++i) {
        dest.SetItemText(line, i, GetItemText(item, i));
      }
      DeleteItem(item);
    }
  }
}

BOOL RSListCtrl::PreTranslateMessage(MSG* pMsg) {
  static constexpr auto startingIndex = 0;
  if (pMsg->message == WM_KEYDOWN &&
      pMsg->wParam == 'A' &&
      Keyboard::IsPressed(VK_CONTROL) &&
      (GetStyle() & LVS_SINGLESEL) == 0) {
    if (IsItemSelected(startingIndex) && IsItemSelected(GetItemCount() - 1)) {
      SetItemState(mfc::noItems, 0, LVIS_SELECTED | LVIS_FOCUSED);
    } else {
      SetItemState(mfc::noItems, LVIS_SELECTED, LVIS_SELECTED);
    }
  }
  return CListCtrl::PreTranslateMessage(pMsg);
}

void RSListCtrl::PreSubclassWindow() {
  CListCtrl::PreSubclassWindow();
  SetExtendedStyle(GetExtendedStyle() | LVS_EX_FULLROWSELECT | LVS_EX_GRIDLINES | LVS_EX_LABELTIP | LVS_EX_DOUBLEBUFFER);
  SetFont(&XTROptions::App().fontTable);
}

BOOL RSListCtrl::IsItemSelected(const int32_t item) {
  return
    item < GetItemCount() &&
    GetItemState(item, LVIS_SELECTED) != 0;
}

} // namespace xtr::ui