//
// Created by Dan Crosby on 9/15/20.
//

#include "MapLoader.hpp"

#include <stdexcept>

#include "src/main/cpp/net/eagle0/common/FilesystemUtils.hpp"

const std::string kShardokMapExtension = ".e0m";

auto LoadMap(const std::string& mapName) -> HexMapProto {
    const std::string mapPath =
            FilesystemUtils::MapFilesDirectory() + mapName + kShardokMapExtension;
    const byte_vector mapProtoBytes = byte_vector::FromPath(mapPath);

    net::eagle0::shardok::common::HexMap mapProto{};
    if (!mapProto.ParseFromArray(mapProtoBytes.data(), static_cast<int>(mapProtoBytes.size()))) {
        throw std::runtime_error("Failed to parse map proto from " + mapPath);
    }

    return mapProto;
}

auto LoadMapFromBytes(const std::string& mapBytes) -> HexMapProto {
    net::eagle0::shardok::common::HexMap mapProto{};
    if (!mapProto.ParseFromString(mapBytes)) {
        throw std::runtime_error("Failed to parse map proto from bytes");
    }

    return mapProto;
}

auto GetMapNames() -> std::vector<std::string> {
    const auto& mapFileNames = FilesystemUtils::FilesInDirectory(
            FilesystemUtils::MapFilesDirectory(),
            kShardokMapExtension);

    std::vector<std::string> names{};
    names.reserve(mapFileNames.size());

    for (const auto& fileName : mapFileNames) {
        names.push_back(fileName.substr(0, fileName.size() - kShardokMapExtension.size()));
    }

    return names;
}
