#pragma once

#include <deque>

#include <util/generic/hash.h>
#include <util/generic/string.h>

namespace NWebmaster {

const int MIRROR_REQUEST_ATTEMPTS = 5;

struct TMirrorResolver {
    using Ptr = TAtomicSharedPtr<TMirrorResolver>;

    TMirrorResolver(std::deque<std::string> &hosts);

    TString ToRobotScheme(TString host);
    void ResolveMirrors(std::deque<std::string> &hosts);
    std::string GetMirror(const std::string &host);

public:
    template<class TContainer>
    typename TContainer::value_type JoinSeq(const TContainer &container, const char *del) {
        typename TContainer::value_type result;
        if (container.empty()) {
            return result;
        }
        auto last = --container.end();
        for (auto it = container.begin(); it != container.end(); ++it) {
            result.append(*it);
            if (it != last) {
                result.append(del);
            }
        }
        return result;
    }

    template<class TIterator>
    typename TIterator::value_type JoinSeq(const TIterator &begin, const TIterator &end, const char *del) {
        typename TIterator::value_type result;
        if (begin == end) {
            return result;
        }
        auto last = std::prev(end);
        for (auto it = begin; it != end; ++it) {
            result.append(*it);
            if (it != last) {
                result.append(del);
            }
        }
        return result;
    }

private:
    THashMap<std::string, std::string> ResolvedMirrors;
    size_t cacheMissesCount = 0;
};

} //namespace NWebmaster
