#pragma once

#include <saas/library/sharding/sharding.h>
#include <string>

namespace NSaas {
    class TErasureUrlConverter {
    public:
        bool InitializeFromFormattedUrl(TStringBuf url);
        bool InitializeFromBaseUrl(TStringBuf url);

        TStringBuf GetBaseUrl() const;
        ui32 GetMainNumber() const;
        ui32 GetParityNumber() const;
        ui32 GetPartNumber() const;
        TString GetFormattedUrl(ui32 part);
        bool SetErasureParams(ui32 main, ui32 parity);
    private:
        TString ConvertNumber(ui32 number) const;
    private:
        TStringBuf baseUrl = "";
        ui32 mainNumber = 0;
        ui32 parityNumber = 0;
        ui32 partNumber = 0;
    };

    class TUrlErasureShardingRule : public TShardsDispatcher::IShardingRule {
    public:
        using TShardsDispatcher::IShardingRule::IShardingRule;
        using TShardsDispatcher::IShardingRule::GetShard;
        virtual NSearchMapParser::TShardIndex GetShard(const TStringBuf& url, TKeyPrefix kps) const override;

        virtual bool CheckSearchInterval(TStringBuf url, TKeyPrefix kps, const TInterval<NSearchMapParser::TShardIndex>& interval) const override;
        virtual bool CheckMessage(const NRTYServer::TMessage& message, TString& error) const override;

        virtual void EnumerateIntervals(TStringBuf url, TKeyPrefix kps, const TShardIntervals& sortedIntervals,
                                        IShardIntervalCallback& callback) const override;

        NSearchMapParser::TShardIndex GetUrlErasureShard(const TStringBuf& url, const NSearchMapParser::TShardIndex shards) const;
    private:
        bool ParseUrl(TStringBuf url, TStringBuf& baseUrl, ui32& mainNumber, ui32& parityNumber, ui32& partNumber) const;
    private:
        static TShardsDispatcher::IShardingRule::TFactory::TRegistrator<TUrlErasureShardingRule> Registrator;
    };
}
