package com.zivilon.cindercore.util;

import java.lang.reflect.Method;
import java.lang.reflect.Field;

import java.util.Vector;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class MethodChecker {

    public static boolean isMethodValid() {
        try {
            Class<?> chunkClass = Class.forName("net.minecraft.world.chunk.Chunk");

            Class<?>[] parameterTypes = new Class[] { byte[].class, int.class, int.class, boolean.class };

            Method fillChunkMethod = chunkClass.getDeclaredMethod("fillChunk", parameterTypes);

            if (fillChunkMethod != null) {
                return true;
            }
        } catch (ClassNotFoundException | NoSuchMethodException | SecurityException e) {
            System.err.println("Failed to validate method: " + e.getMessage());
        }
        return false;
    }

    public static void main() {
        boolean isValid = isMethodValid();
    }

    public static void dumpClass(String className, String outputFilePath, Class<?> contextClass) {
        String resourcePath = className.replace('.', '/') + ".class";
        try (InputStream classStream = contextClass.getClassLoader().getResourceAsStream(resourcePath)) {
            if (classStream == null) {
                System.err.println("Class " + className + " could not be found.");
                return;
            }
            try (OutputStream outputStream = new FileOutputStream(outputFilePath)) {
                byte[] buffer = new byte[4096];
                int bytesRead;
                while ((bytesRead = classStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }
                System.out.println("Dumped " + className + " to " + outputFilePath);
            } catch (IOException e) {
                System.err.println("Failed to write class file: " + e.getMessage());
            }
        } catch (IOException e) {
            System.err.println("Failed to read class file: " + e.getMessage());
        }
    }

    public static void printLoadedClasses() {
        try {
            ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader();

            Field classesField = ClassLoader.class.getDeclaredField("classes");
            classesField.setAccessible(true);

            @SuppressWarnings("unchecked")
            Vector<Class<?>> classes = (Vector<Class<?>>) classesField.get(systemClassLoader);

            for (Class<?> clazz : classes) {
                System.out.println(clazz.getName());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
