#include "screens/components/VoteViewModel.hpp" #include "api/DevPlaceApi.hpp" #include "screens/AppContext.hpp" #include "screens/components/AlertPresenter.hpp" #include "screens/post/ModelCache.hpp" #include "store/AppState.hpp" namespace dp { namespace { ModelCache& cache() { static ModelCache c; return c; } } // namespace VoteViewModel::VoteViewModel(TargetType type, std::string targetId, std::int64_t count, Vote vote) : type_(type), targetId_(std::move(targetId)), count_(count), vote_(vote), propCount_(count), propVote_(vote) {} std::shared_ptr VoteViewModel::shared(TargetType type, const std::string& targetId, std::int64_t count, Vote vote) { auto model = cache().get(std::string(type.raw()) + ":" + targetId, [&] { auto m = std::make_shared(type, targetId, count, vote); m->self_ = m; return m; }); model->syncProps(count, vote); return model; } void VoteViewModel::clearCache() { cache().clear(); } void VoteViewModel::syncProps(std::int64_t count, Vote vote) { if (count != propCount_) { propCount_ = count; count_ = count; } if (vote != propVote_) { propVote_ = vote; vote_ = vote; } } bool VoteViewModel::userCanVote() const { return AppState::instance().isLoggedIn(); } Vote VoteViewModel::nextVote(Vote current, Vote tapped) { return current == tapped ? Vote(Vote::None) : tapped; } std::int64_t VoteViewModel::nextCount(std::int64_t count, Vote previous, Vote next) { return count + next.value() - previous.value(); } void VoteViewModel::voteUp() { if (loading_) return; apply(Vote(Vote::Up), nextVote(vote_, Vote(Vote::Up))); } void VoteViewModel::voteDown() { if (loading_) return; apply(Vote(Vote::Down), nextVote(vote_, Vote(Vote::Down))); } void VoteViewModel::apply(Vote selected, Vote newVote) { loading_ = true; const Vote previousVote = vote_; const std::int64_t previousCount = count_; vote_ = newVote; count_ = nextCount(previousCount, previousVote, newVote); syncToFeed(); auto keep = self_.lock(); AppContext::api().vote(type_, targetId_, selected, [this, keep, previousVote, previousCount](Result r) { loading_ = false; if (r.ok()) return; vote_ = previousVote; count_ = previousCount; syncToFeed(); AlertPresenter::showError(r.error()); }); } void VoteViewModel::syncToFeed() const { if (type_ == TargetType::Post) AppState::instance().updatePostVoteInFeed(targetId_, vote_, count_); else if (type_ == TargetType::Comment) AppState::instance().updateCommentVoteInFeed(targetId_, vote_); } } // namespace dp