package core.engine;

import core.engine.entity.Camera;
import core.engine.entity.Entity;
import core.engine.entity.Light;
import core.engine.model.HexagonModel;
import core.engine.model.RawModel;
import core.engine.model.TexturedModel;
import core.engine.renderer.MasterRenderer;
import core.engine.terrain.Terrain;
import core.engine.textures.ModelTexture;
import core.engine.toolbox.MousePicker;
import org.lwjgl.BufferUtils;
import org.lwjgl.Version;
import org.lwjgl.glfw.*;
import org.lwjgl.opengl.GL;
import org.lwjgl.system.MemoryStack;
import utils.vectors.Vector3f;

import java.nio.DoubleBuffer;
import java.nio.IntBuffer;

import static org.lwjgl.glfw.Callbacks.glfwFreeCallbacks;
import static org.lwjgl.glfw.GLFW.*;
import static org.lwjgl.glfw.GLFW.glfwSwapBuffers;
import static org.lwjgl.opengl.GL11.glClearColor;
import static org.lwjgl.system.MemoryStack.stackPush;
import static org.lwjgl.system.MemoryUtil.NULL;

public class Engine {

    private long window;
    private GLFWKeyCallback glfwKeyCallback;
    private final Loader loader = new Loader();
    public static int WINDOW_WIDTH = 1280;
    public static int WINDOW_HEIGHT = 720;
    private static boolean isMouseWheelPressed = false;
    private static DoubleBuffer lastCursorX = BufferUtils.createDoubleBuffer(1);
    private static DoubleBuffer lastCursorY = BufferUtils.createDoubleBuffer(1);


    public Engine() {

        System.out.println("Hello LWJGL " + Version.getVersion() + "!");

        init();
        loop();

        // Free the window callbacks and destroy the window
        glfwFreeCallbacks(window);
        glfwDestroyWindow(window);

        // Terminate GLFW and free the error callback
        glfwTerminate();
        glfwSetErrorCallback(null).free();
    }

    private void init() {
        // Setup an error callback. The default implementation
        // will print the error message in System.err.
        GLFWErrorCallback.createPrint(System.err).set();

        // Initialize GLFW. Most GLFW functions will not work before doing this.
        if ( !glfwInit() )
            throw new IllegalStateException("Unable to initialize GLFW");

        // Configure GLFW
        glfwDefaultWindowHints(); // optional, the current window hints are already the default
        glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE); // the window will stay hidden after creation
        glfwWindowHint(GLFW_RESIZABLE, GLFW_FALSE); // the window will be resizable

        // Create the window
        window = glfwCreateWindow(1280, 720, "Hello World!", NULL, NULL);
        if ( window == NULL )
            throw new RuntimeException("Failed to create the GLFW window");

        // Setup a key callback. It will be called every time a key is pressed, repeated or released.
        glfwSetKeyCallback(window, (window, key, scancode, action, mods) -> {
            if ( key == GLFW_KEY_ESCAPE && action == GLFW_RELEASE )
                glfwSetWindowShouldClose(window, true); // We will detect this in the rendering loop
        });

        // Get the thread stack and push a new frame
        try ( MemoryStack stack = stackPush() ) {
            IntBuffer pWidth = stack.mallocInt(1); // int*
            IntBuffer pHeight = stack.mallocInt(1); // int*

            // Get the window size passed to glfwCreateWindow
            glfwGetWindowSize(window, pWidth, pHeight);

            // Get the resolution of the primary monitor
            GLFWVidMode vidmode = glfwGetVideoMode(glfwGetPrimaryMonitor());

            // Center the window
            glfwSetWindowPos(
                    window,
                    (vidmode.width() - pWidth.get(0)) / 2,
                    (vidmode.height() - pHeight.get(0)) / 2
            );
        } // the stack frame is popped automatically

        // Make the OpenGL context current
        glfwMakeContextCurrent(window);
        // Enable v-sync
        glfwSwapInterval(1);

        // Make the window visible
        glfwShowWindow(window);
    }

    private void loop() {
        // This line is critical for LWJGL's interoperation with GLFW's
        // OpenGL context, or any context that is managed externally.
        // LWJGL detects the context that is current in the current thread,
        // creates the GLCapabilities instance and makes the OpenGL
        // bindings available for use.
        GL.createCapabilities();

        // Set the clear color
        glClearColor(1.0f, 0.0f, 0.0f, 0.0f);
        Camera camera = new Camera();

        Light light = new Light(new Vector3f(0,0,-20), new Vector3f(1,1,1));

        //Generate Simple, Flat Terrain
        Terrain terrain = new Terrain( loader, new ModelTexture(loader.loadTexture("white")), 16, 16, 7);

        //Create Hexagon
        HexagonModel hexagonModel = new HexagonModel();
        RawModel hexagonRawModel = loader.loadHexagon(hexagonModel);
        ModelTexture hexagonTexture = new ModelTexture(loader.loadTexture("white"));
        TexturedModel hexagontexturedModel = new TexturedModel(hexagonRawModel, hexagonTexture);
        Entity hexagonEntity = new Entity(hexagontexturedModel, new Vector3f(0,1,0), 0,0,0,1);

        // Run the rendering loop until the user has attempted to close
        // the window or has pressed the ESCAPE key.
        MasterRenderer renderer = new MasterRenderer();
        MousePicker mousePicker = new MousePicker(camera, renderer.getProjectionMatrix(), terrain);
        input(camera, renderer, mousePicker);
        while ( !glfwWindowShouldClose(window) ) {
            renderer.processTerrain(terrain);

            //renderer.processEntity(hexagonEntity);
            renderer.render(light, camera);
            DoubleBuffer posX = BufferUtils.createDoubleBuffer(1);
            DoubleBuffer posY = BufferUtils.createDoubleBuffer(1);
            glfwGetCursorPos(window, posX, posY);
            mousePicker.update((float) posX.get(0), (float) posY.get(0));
            glfwSwapBuffers(window); // swap the color buffers
            // Poll for window events. The key callback above will only be
            // invoked during this call.
            glfwPollEvents();
        }
        renderer.cleanUp();
        loader.cleanUp();
    }

    private void input(Camera camera, MasterRenderer masterRenderer, MousePicker mousePicker) {

        GLFWScrollCallback glfwScrollCallback = new GLFWScrollCallback() {
            @Override
            public void invoke(long window, double xOffset, double yOffset) {
                if(yOffset > 0) {
                    camera.zoomIn();
                } else if(yOffset < 0) {
                    camera.zoomOut();
                }
            }
        };

        GLFWMouseButtonCallback glfwMouseButtonCallback = new GLFWMouseButtonCallback() {
            @Override
            public void invoke(long window, int button, int action, int mods) {
                if (button == GLFW.GLFW_MOUSE_BUTTON_MIDDLE && action == GLFW.GLFW_PRESS) {
                    // Middle mouse button pressed
                    isMouseWheelPressed = true;
                    glfwGetCursorPos(window, lastCursorX, lastCursorY);
                } else if (button == GLFW.GLFW_MOUSE_BUTTON_MIDDLE && action == GLFW.GLFW_RELEASE) {
                    // Middle mouse button released
                    isMouseWheelPressed = false;
                }

                if(button == GLFW_MOUSE_BUTTON_LEFT && action == GLFW_PRESS) {
                    //Track mouse position
                    DoubleBuffer posX = BufferUtils.createDoubleBuffer(1);
                    DoubleBuffer posY = BufferUtils.createDoubleBuffer(1);
                    glfwGetCursorPos(window, posX, posY);
                    System.out.println(posX.get(0) + "|" + posY.get(0));
                    mousePicker.update((float) posX.get(0), (float) posY.get(0));
                    mousePicker.calcIntersectingTerrainTile();
                }
            }
        };

        // Define the cursor position callback function
        GLFWCursorPosCallback cursorPosCallback = new GLFWCursorPosCallback() {
            @Override
            public void invoke(long window, double xpos, double ypos) {
                if (isMouseWheelPressed) {
                    // Calculate the offset
                    double xOffset = xpos - lastCursorX.get(0);
                    double yOffset = ypos - lastCursorY.get(0);

                    // Use xOffset and yOffset for your desired functionality
                    if(yOffset > 0) {
                        camera.decreasePitch();
                    } else if(yOffset < 0) {
                        camera.increasePitch();
                    }

                    if(xOffset > 0) {
                        camera.decreaseYaw();
                    } else if(xOffset < 0) {
                        camera.increaseYaw();
                    }

                    // Update the last cursor position
                    lastCursorX.put(0, xpos);
                    lastCursorY.put(0, ypos);
                }
            }
        };

        glfwSetMouseButtonCallback(window, glfwMouseButtonCallback);
        glfwSetCursorPosCallback(window, cursorPosCallback);

        glfwSetScrollCallback(window, glfwScrollCallback);
        glfwSetKeyCallback(window, glfwKeyCallback = new GLFWKeyCallback() {
            @Override
            public void invoke(long window, int key, int scancode, int action, int mods) {
                if(key == GLFW_KEY_A) {
                    //move camera to left
                    camera.moveLeft();
                }

                if(key == GLFW_KEY_D) {
                    //move camera to right
                    camera.moveRight();
                }

                if(key == GLFW_KEY_W) {
                    camera.moveForward();
                }

                if(key == GLFW_KEY_S) {
                    camera.moveBackward();
                }

                if(key == GLFW_KEY_Y && action == GLFW_PRESS) {
                    masterRenderer.switchWireframe();
                }
            }
        });



    }

}
