#pragma once
#include <saas/library/searchmap/slots_pool.h>
#include <saas/library/sharding/sharding.h>
#include <util/string/vector.h>

namespace NDaemonController {

    class TIntervalsByDC {
    private:
        TMap<TString, TVector<NSearchMapParser::TShardsInterval>> IntervalsByDC;
    public:

        const TMap<TString, TVector<NSearchMapParser::TShardsInterval>>& GetInfo() const {
            return IntervalsByDC;
        }

        bool HasDC(const TString& dcName) const {
            return IntervalsByDC.contains(dcName);
        }

        ui32 Size() const {
            ui32 result = 0;
            for (auto&& i : IntervalsByDC) {
                result += i.second.size();
            }
            return result;
        }

        void AddInfo(const TString& dcName, const NSearchMapParser::TShardsInterval& interval) {
            IntervalsByDC[dcName].push_back(interval);
        }

        bool AddInfoUniq(const TString& dcName, const NSearchMapParser::TShardsInterval& interval) {
            for (ui32 i = 0; i < IntervalsByDC[dcName].size(); ++i) {
                if (IntervalsByDC[dcName][i] == interval)
                    return false;
            }
            AddInfo(dcName, interval);
            return true;
        }

        bool DeserializeFromJson(const NJson::TJsonValue& value) {
            IntervalsByDC.clear();
            if (!value.IsMap())
                return false;

            for (const auto& i : value.GetMap()) {
                if (!i.second.IsArray())
                    return false;
                for (const auto& interval : i.second.GetArray()) {
                    if (!interval.IsMap())
                        return false;
                    if (!interval.Has("min") || !interval.Has("max"))
                        return false;
                    IntervalsByDC[i.first].push_back(NSearchMapParser::TShardsInterval(interval["min"].GetIntegerRobust(), interval["max"].GetIntegerRobust()));
                }
            }
            return true;
        }

        NJson::TJsonValue SerializeToJson() const {
            NJson::TJsonValue result;
            for (auto&& i : IntervalsByDC) {
                for (auto&& interval : i.second) {
                    NJson::TJsonValue intervalJson;
                    intervalJson.InsertValue("min", interval.GetMin());
                    intervalJson.InsertValue("max", interval.GetMax());
                    result[i.first].AppendValue(std::move(intervalJson));
                }
            }
            return result;
        }
    };
}
