#pragma once

#include "signature.h"

#include <util/generic/ptr.h>
#include <util/stream/file.h>
#include <util/string/vector.h>
#include <util/string/split.h>

namespace NModAntiDDOS {
    THolder<IInputStream> GetTemplate(const TString& name);

    class TRedirectionTemplate {
    public:
        TRedirectionTemplate()
            : ChunkLength_(0) {
        }

        TRedirectionTemplate(const TString& filename)
            : ChunkLength_(0) {
                Load(filename);
        }

        void Write(const TSignedTarget& target, IOutputStream& out) const noexcept {
            auto chunk = Chunks_.cbegin();
            if (chunk == Chunks_.cend()) {
                return;
            }

            out << *chunk;
            for (++chunk; chunk != Chunks_.end(); ++chunk) {
                out << target << *chunk;
            }
        }

        size_t Length(const TSignedTarget& target) const noexcept {
            return Chunks_.size() == 0 ? 0 : ChunkLength_ + target.Length() * (Chunks_.size() - 1);
        }

        void Load(IInputStream& input) {
            StringSplitter(input.ReadAll()).SplitByString("%URL%").SkipEmpty().Collect(&Chunks_);
            ChunkLength_ = 0;
            for (TVector<TString>::const_iterator chunk = Chunks_.begin(); chunk != Chunks_.end(); ++chunk) {
                ChunkLength_ += chunk->length();
            }
        }

        void Load(const TString& filename) {
            Load(*GetTemplate(filename));
        }

    private:
        TVector<TString> Chunks_;
        size_t ChunkLength_;
    };
}
