#pragma once

#include "vmMeta.hpp"

#include "ccl/lang/RefsManager.h"

namespace xtr::viewmodel {

struct HighlightItem {
  StrRange rng{};
  COLORREF color{};
};

//! Abstract interface for TextEdit control
struct ITextEdit {
  [[nodiscard]] virtual CString GetText() const = 0;
  virtual void SetText(CString newText) = 0;
  virtual void ReplaceRange(StrRange range, CString replacement) = 0;

  virtual void Highlight(HighlightItem item) = 0;
  [[nodiscard]] virtual std::optional<HighlightItem> NextHighlighted(StrPos start) = 0;
};

//! Presenter: TextEdit
class vmTextEdit {
  ITextEdit& control;

  bool outdated{ true };
  const ccl::lang::EntityTermContext* context{ nullptr };
  ccl::lang::RefsManager references{};

public:
  explicit vmTextEdit(ITextEdit& control) noexcept
    : control{ control } {}
  void Initialize(const ccl::lang::EntityTermContext& cntxt) noexcept;

public:
  void SetRefStr(CString refStr);

  [[nodiscard]] const ccl::lang::EntityTermContext& Context() const noexcept { return *context; }

  [[nodiscard]] CString GetRefStr();
  [[nodiscard]] CString GetRefSubstr(StrRange cr);

  void Invalidate() noexcept { outdated = true; }

  void OnEraseText(StrRange range, BOOL lookBehind);
  void OnInsertRef(ccl::StrRange rWhere, ccl::lang::Reference data);
  [[nodiscard]] const ccl::lang::Reference* RepresentativeOf(StrRange range);

private:
  void UpdateData();
};

} // namespace xtr::viewmodel