#pragma once

#include <filesystem>
#include <functional>
#include <memory>
#include <string>

namespace maps::mrc::import_taxi {

/**
 * User of a dataset, refreshable on demand.
 * Upon refresh it recreates itself if dataset path has changed.
 * Not thread-safe.
 */
template <typename T>
class DatasetUser {
public:
    using DatasetOpener = std::function<std::shared_ptr<T>(const std::string& path)>;

    DatasetUser(const std::string& path, DatasetOpener datasetOpener)
        : symlinkPath_(path)
        , canonicalPath_(std::filesystem::canonical(symlinkPath_))
        , datasetOpener_(std::move(datasetOpener))
        , userPtr_(datasetOpener_(canonicalPath_))
    {}

    std::shared_ptr<T> get() const { return userPtr_; }

    void refresh()
    {
        auto newCanonicalPath = std::filesystem::canonical(symlinkPath_);

        if (newCanonicalPath != canonicalPath_) {
            canonicalPath_ = std::move(newCanonicalPath);
            userPtr_ = datasetOpener_(canonicalPath_);
        }
    }

private:
    std::filesystem::path symlinkPath_;
    std::filesystem::path canonicalPath_;
    DatasetOpener datasetOpener_;
    std::shared_ptr<T> userPtr_;
};


} // namespace maps::mrc::import_taxi
