#pragma once
#include <maps/wikimap/mapspro/tools/ymapsdf-conversion/json2ymapsdf/lib/ymapsdf/record.h>

#include <unordered_map>
#include <mutex>
#include <atomic>

namespace maps::wiki::json2ymapsdf {

class IncompleteRecords {
public:
    IncompleteRecords();

    void add(ymapsdf::Record&& record);
    ymapsdf::Records popRecords(const std::string& key);
    ymapsdf::Records popRecords();

    std::string stat() const;

    size_t size() const { return size_; }

private:
    using RecordsMap = std::unordered_map<std::string, ymapsdf::Records>;
    using StatiscticsMap = std::unordered_map<const ymapsdf::schema::Table *, size_t>;

private:
    ymapsdf::Records popRecords(RecordsMap::iterator it);

private:
    RecordsMap records_;
    StatiscticsMap statistics_;
    std::atomic<size_t> size_;
};

class IncompleteManager {
public:
    IncompleteManager() = default;

    void mergeIncomplete(ymapsdf::Records& records);
    ymapsdf::Records popRecords();
    std::string stat() const;
    size_t size() const;

    size_t waiters() const { return waiters_; }

private:
    void subjoinIncomplete(ymapsdf::Records& records);

    IncompleteRecords incompleteRecords_;

    mutable std::mutex mutex_;
    std::atomic<size_t> waiters_{0};
};

} // namespace maps::wiki::json2ymapsdf
