#include "get_subscriptions.h"
#include <maps/wikimap/mapspro/services/editor/src/exception.h>
#include <maps/wikimap/mapspro/services/editor/src/configs/config.h>
#include <maps/wikimap/mapspro/services/editor/src/branch_helpers.h>

#include <yandex/maps/wiki/configs/editor/categories.h>
#include <yandex/maps/wiki/revision/revisionsgateway.h>
#include <yandex/maps/wiki/revision/filters.h>
#include <yandex/maps/wiki/social/gateway.h>

namespace maps {
namespace wiki {

GetSocialSubscriptions::GetSocialSubscriptions(const Request& request)
    : controller::BaseController<GetSocialSubscriptions>(BOOST_CURRENT_FUNCTION)
    , request_(request)
{ }

std::string
GetSocialSubscriptions::printRequest() const
{
    std::stringstream ss;
    ss << " uid: " << request_.user
       << " token: " << request_.token;
    return ss.str();
}

void
GetSocialSubscriptions::control()
{
    auto branchCtx = BranchContextFacade().acquireReadCoreSocial(request_.token);

    auto console = social::Gateway(branchCtx.txnSocial())
        .subscriptionConsole(request_.user);
    auto subscriptions = console.subscriptions();

    if (subscriptions.empty()) {
        return;
    }

    std::vector<TOid> regionIds;
    for (const auto& subscription : subscriptions) {
        regionIds.push_back(subscription.feedId());
    }

    namespace rf = revision::filters;
    auto revisionGw = revision::RevisionsGateway(branchCtx.txnCore());
    auto snapshot = revisionGw.snapshot(revisionGw.headCommitId());
    auto regions = snapshot.objectRevisionsByFilter(
            rf::ObjRevAttr::objectId().in(regionIds)
            && rf::ObjRevAttr::isNotRelation()
            && rf::Geom::defined()
            && rf::ObjRevAttr::isNotDeleted());

    for (const auto& region : regions) {
        const auto& data = region.data();
        ASSERT(!data.deleted);
        ASSERT(data.attributes);
        auto nameIt = data.attributes->find(ATTR_FEED_REGION_NAME);
        std::string title;
        if (nameIt != data.attributes->end() && !nameIt->second.empty()) {
            title = nameIt->second;
        } else {
            title = cfg()->editor()->categories()[CATEGORY_FEED_REGION].label();
        }
        result_->regionIdToTitle.insert({region.id().objectId(), title});
    }
}

} // namespace wiki
} // namespace maps
