#pragma once

#include "ccl/rslang/SDataCompact.h"
#include "xtr/doc/RSModelDoc.h"

namespace xtr::ui {

//! Control: Edit structured data in table
class DataGridCtrl final : public CListCtrl {
  BOOL isModified{ FALSE };

  doc::RSModelDoc* m_Doc{ nullptr };
  ccl::semantic::RSModel* model{ nullptr };

  EntityUID activeCst{};
  std::vector<std::optional<EntityUID>> headerIDs{};

  CToolTipCtrl  tooltips{};
  CComboBox* editCtrl{ nullptr };

  BOOL showText{ FALSE };
  BOOL isEditable{ FALSE };
  BOOL isBasic{ FALSE };
  const ccl::rslang::Typification* typification{ nullptr };

  // Selected cell state
  int32_t columnCount{ 0 };
  // Note: Число строк можно получить командой GetItemCount

  int32_t topIndex{};
  int32_t ensureVisible;

  int32_t selectedRow;
  int32_t selectedColumn;

public:
  DataGridCtrl();  

public:
  void Init(CComboBox* box, BOOL textFlag, doc::RSModelDoc& _doc);
  [[nodiscard]] BOOL IsInit() const noexcept { 
    return model != nullptr;
  
  }
  void SetActive(EntityUID activeUID);
  void SetTextFlag(BOOL flag);

  [[nodiscard]] ccl::object::SDCompact::Data GetIDTable() const;

  void SaveData();
  void UpdateSelectedCellText();

private:
  BOOL PreTranslateMessage(MSG* pMsg) override;

DECLARE_MESSAGE_MAP()
  afx_msg void OnSetFocus(CWnd* pOldWnd);
  afx_msg void OnMouseMove(uint32_t nFlags, CPoint point);
  afx_msg void OnClick(NMHDR* pNMHDR, LRESULT* pResult);
  afx_msg void OnDbClick(NMHDR* pNMHDR, LRESULT* pResult);
  afx_msg void OnKeydown(NMHDR* pNMHDR, LRESULT* pResult);
  afx_msg void OnCustomDraw(NMHDR *pNMHDR, LRESULT *pResult);
  afx_msg void OnPaint();

private:
  void InitToolTips();
  void UpdateToolTipText(int32_t row, int32_t col);

  void ReloadData();
  void Clear();

  void LoadBasicData();
  void CreateBasicHeader(CString basicName);
  void InputTextData(const ccl::semantic::TextInterpretation & input);

  void LoadSData();
  void CreateHeader();
  void InputStructuredtData(const ccl::object::SDCompact::Data& data);

  void InvalidateCell(int32_t row, int32_t col);
  void ShowEditWindowAtCell(int32_t row, int32_t col);

  void OnFirstDraw();
  void OnDrawItem(NMLVCUSTOMDRAW& drawer);

  void CopyCurrentRow();
  void DeleteCurrentRow();
  int32_t AddBaseRow();
  [[nodiscard]] int32_t GetMaxIndex() const;

  void SortData();
  void SwapItems(int32_t item1, int32_t item2);
  [[nodiscard]] int32_t CompareItems(int32_t item1, int32_t item2) const;

  void SetTableItem(int32_t row, int32_t col, CString text);
};

} // namespace xtr::ui