// 
// Decompiled by Procyon v0.6.0
// 

package com.hypixel.hytale.builtin.hytalegenerator.assets.props.prefabprop;

import javax.annotation.Nullable;
import org.bson.BsonDocument;
import com.hypixel.hytale.server.core.prefab.selection.buffer.BsonPrefabBufferDeserializer;
import com.hypixel.hytale.server.core.util.BsonUtil;
import java.io.IOException;
import com.hypixel.hytale.builtin.hytalegenerator.LoggerUtil;
import com.hypixel.hytale.common.util.ExceptionUtil;
import java.nio.file.FileVisitor;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import com.hypixel.hytale.server.core.prefab.selection.buffer.impl.PrefabBuffer;
import java.util.List;
import javax.annotation.Nonnull;
import java.nio.file.Path;

public class PrefabLoader
{
    @Nonnull
    public static void loadAllPrefabBuffersUnder(@Nonnull final Path dirPath, final List<PrefabBuffer> pathPrefabs) {
        if (Files.isDirectory(dirPath, new LinkOption[0])) {
            try {
                Files.walkFileTree(dirPath, new PrefabFileVisitor(pathPrefabs));
            }
            catch (final IOException e) {
                String msg = "Exception thrown by HytaleGenerator while loading a Prefab:\n";
                msg += ExceptionUtil.toStringWithStack(e);
                LoggerUtil.getLogger().severe(msg);
            }
            return;
        }
        final PrefabBuffer prefab = loadPrefabBufferAt(dirPath);
        if (prefab == null) {
            return;
        }
        pathPrefabs.add(prefab);
    }
    
    @Nullable
    public static PrefabBuffer loadPrefabBufferAt(@Nonnull final Path filePath) {
        if (!hasJsonExtension(filePath)) {
            return null;
        }
        try {
            final BsonDocument prefabAsBson = BsonUtil.readDocumentNow(filePath);
            if (prefabAsBson == null) {
                return null;
            }
            return BsonPrefabBufferDeserializer.INSTANCE.deserialize(filePath, prefabAsBson);
        }
        catch (final Exception e) {
            String msg = "Exception thrown by HytaleGenerator while loading a PrefabBuffer for " + String.valueOf(filePath) + ":\n";
            msg += ExceptionUtil.toStringWithStack(e);
            LoggerUtil.getLogger().severe(msg);
            return null;
        }
    }
    
    public static boolean hasJsonExtension(@Nonnull final Path path) {
        final String pathString = path.toString();
        return pathString.toLowerCase().endsWith(".json");
    }
}
