Skip to content
Repos

DevPlaceApp

C++ 2.6 KB79 lines Opens in site

Directory Raw Download

#include "screens/components/ReportViewModel.hpp"

#include "screens/AppContext.hpp"
#include "screens/components/AlertPresenter.hpp"
#include "core/TextCount.hpp"
#include "screens/post/ModelCache.hpp"
#include "spec/ModelLimits.hpp"
#include "spec/PostsSpec.hpp"

namespace dp {

namespace {
ModelCache<ReportViewModel>& cache() {
  static ModelCache<ReportViewModel> c;
  return c;
}
}  // namespace

ReportViewModel::ReportViewModel(TargetType type, std::string targetId) : type_(type), targetId_(std::move(targetId)) {}

std::shared_ptr<ReportViewModel> ReportViewModel::shared(TargetType type, const std::string& targetId) {
  return cache().get(std::string(type.raw()) + ":" + targetId, [&] {
    auto m = std::make_shared<ReportViewModel>(type, targetId);
    m->self_ = m;
    return m;
  });
}

void ReportViewModel::clearCache() { cache().clear(); }

std::string ReportViewModel::targetNoun() const {
  return type_ == TargetType::Comment ? spec::PostsText::kNounComment : spec::PostsText::kNounPost;
}

std::string ReportViewModel::sheetTitle() const { return std::string(spec::PostsText::kReportSheetPrefix) + targetNoun(); }

std::size_t ReportViewModel::detailLimit() const { return spec::ModelLimits::kMaxReportDetailLength; }

bool ReportViewModel::isDetailWithinLimit() const { return static_cast<std::size_t>(TextCount::utf16(detail)) <= detailLimit(); }

bool ReportViewModel::canSubmit() const { return selected_.has_value() && !submitting_ && isDetailWithinLimit(); }

void ReportViewModel::prepareForPresentation() {
  selected_.reset();
  detail.clear();
}

void ReportViewModel::loadReasons() {
  if (!reasons_.empty() || loading_) return;
  loading_ = true;
  failed_ = false;
  auto keep = self_.lock();
  AppContext::api().reportReasons([this, keep](Result<std::vector<ReportReason>> r) {
    loading_ = false;
    if (r.ok()) reasons_ = r.value();
    else failed_ = true;
  });
}

std::optional<std::string> ReportViewModel::trimmedDetail(const std::string& text) {
  const char* ws = " \t\n\r\f\v";
  const std::size_t b = text.find_first_not_of(ws);
  if (b == std::string::npos) return std::nullopt;
  const std::size_t e = text.find_last_not_of(ws);
  return text.substr(b, e - b + 1);
}

void ReportViewModel::submit(std::function<void(bool)> done) {
  if (!selected_ || submitting_) return;
  submitting_ = true;
  auto keep = self_.lock();
  AppContext::api().report(type_, targetId_, *selected_, trimmedDetail(detail), [this, keep, done = std::move(done)](Result<Unit> r) {
    submitting_ = false;
    if (!r.ok()) AlertPresenter::showError(r.error());
    if (done) done(r.ok());
  });
}

}  // namespace dp
45.4ms