#include <spdlog/spdlog.h>
#include "./editing.hpp"

namespace lsp::service::symbol::repository
{
    void Editing::AddOrUpdate(EditingSymbolTable table)
    {
        std::unique_lock lock(mutex_);
        const auto& uri = table.uri;
        auto version = table.version;

        documents_[uri] = std::move(table);
        spdlog::debug("Added/Updated editing document: {} (v{})", uri, version);
    }

    void Editing::Remove(const protocol::DocumentUri& uri)
    {
        std::unique_lock lock(mutex_);
        documents_.erase(uri);
        spdlog::debug("Removed editing document: {}", uri);
    }

    bool Editing::Contains(const protocol::DocumentUri& uri) const
    {
        std::shared_lock lock(mutex_);
        return documents_.find(uri) != documents_.end();
    }

    void Editing::Clear()
    {
        std::unique_lock lock(mutex_);
        documents_.clear();
        spdlog::debug("Cleared all editing documents");
    }

    size_t Editing::Count() const
    {
        std::shared_lock lock(mutex_);
        return documents_.size();
    }

    // ==================== 符号表访问 ====================

    const language::symbol::SymbolTable* Editing::GetSymbolTable(const protocol::DocumentUri& uri) const
    {
        std::shared_lock lock(mutex_);
        auto it = documents_.find(uri);
        if (it == documents_.end() || !it->second.symbol_table)
            return nullptr;
        return it->second.symbol_table.get();
    }

    std::optional<TsfFileType> Editing::GetFileType(const protocol::DocumentUri& uri) const
    {
        std::shared_lock lock(mutex_);
        auto it = documents_.find(uri);
        return (it != documents_.end()) ? std::optional{ it->second.file_type } : std::nullopt;
    }

    std::optional<protocol::integer> Editing::GetVersion(const protocol::DocumentUri& uri) const
    {
        std::shared_lock lock(mutex_);
        auto it = documents_.find(uri);
        return (it != documents_.end()) ? std::optional{ it->second.version } : std::nullopt;
    }

}
