#include "mapping.h"

#include <library/cpp/logger/global/global.h>

#include <kernel/index_mapping/index_mapping.h>

#include <util/folder/path.h>
#include <util/system/filemap.h>

using namespace NRTYServer;

void NRTYServer::EnableGlobalMapping(bool IsReadOnly) {
    EnableGlobalIndexFileMapping();
    if (!IsReadOnly) {
        EnableWritableMapping();
    }
}

THolder<TFileMap> NRTYServer::GetFileMapping(const TString& filename) {
    // Trying to get global index mapping first
    const TMemoryMap* global = GetMappedIndexFile(filename);
    if (global) {
        INFO_LOG << "Using global file mapping for " << filename << Endl;
        return THolder(new TFileMap(*global));
    }

    // Global mapping is not available
    // There are two possibilities: opening file with global mapping settings or
    // making additional argument for open mode. If we could make global mapping with different open modes...
    return GetTempFileMapping(filename, false);
}

THolder<TFileMap> NRTYServer::GetTempFileMapping(const TString& filename, bool IsReadOnly) {
    if (IsReadOnly) {
        return THolder(new TFileMap(filename));
    }
    return THolder(new TFileMap(filename, TFileMap::oRdWr));
}

void NRTYServer::ReleaseFileMapping(const TString& filename) {
    ReleaseMappedIndexFile(filename);
}
