import org.lwjgl.BufferUtils;
import org.lwjgl.glfw.*;
import org.lwjgl.opengl.GL;
import org.lwjgl.system.MemoryStack;
import static org.lwjgl.stb.STBImage.*;
import static org.lwjgl.stb.STBImageResize.*;

import static org.lwjgl.glfw.GLFW.*;
import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.system.MemoryUtil.*;
import static org.lwjgl.system.MemoryStack.*;
import static org.lwjgl.BufferUtils.*;

import java.io.InputStream;
import java.nio.*;
import java.nio.channels.*;
import java.nio.file.*;

import java.io.*;

public class ugr08 {

	private static ByteBuffer resizeBuffer(ByteBuffer buffer, int newCapacity) {
        ByteBuffer newBuffer = BufferUtils.createByteBuffer(newCapacity);
        buffer.flip();
        newBuffer.put(buffer);
        return newBuffer;
}	
	private ByteBuffer ioResourceToByteBuffer(String resource, int bufferSize) throws IOException {
        ByteBuffer buffer;

        Path path = Paths.get(resource);
        if (Files.isReadable(path)) {
            try (SeekableByteChannel fc = Files.newByteChannel(path)) {
                buffer = BufferUtils.createByteBuffer((int)fc.size() + 1);
                while (fc.read(buffer) != -1) {
                    ;
                }
            }
        } else {
            try (
                InputStream source = this.getClass().getClassLoader().getResourceAsStream(resource);
                ReadableByteChannel rbc = Channels.newChannel(source)
            ) {
                buffer = createByteBuffer(bufferSize);

                while (true) {
                    int bytes = rbc.read(buffer);
                    if (bytes == -1) {
                        break;
                    }
                    if (buffer.remaining() == 0) {
                        buffer = resizeBuffer(buffer, buffer.capacity() * 3 / 2); // 50%
                    }
                }
            }
        }

        buffer.flip();
        return buffer.slice();
    }
	
	
	 private int createTexture(String Path) {
	        int texID = glGenTextures();
	        ByteBuffer imageBuffer;
	        try {
	            imageBuffer = ioResourceToByteBuffer(Path, 8 * 1024);
	        } catch (Exception e) {
	            throw new RuntimeException(e);
	        }
            int w,h,comp;
            ByteBuffer image;
	        try (MemoryStack stack = stackPush()) {
	            IntBuffer wB    = stack.mallocInt(1);
	            IntBuffer hB    = stack.mallocInt(1);
	            IntBuffer compB = stack.mallocInt(1);

	            // Use info to read image metadata without decoding the entire image.
	            // We don't need this for this demo, just testing the API.
	            if (!stbi_info_from_memory           		
	            		
	            		(imageBuffer, wB, hB, compB)) {
	                throw new RuntimeException("Failed to read image information: " + stbi_failure_reason());
	            }

/*	            System.out.println("Image width: " + wB.get(0));
	            System.out.println("Image height: " + hB.get(0));
	            System.out.println("Image components: " + compB.get(0));
	            System.out.println("Image HDR: " + stbi_is_hdr_from_memory(imageBuffer));*/

	            // Decode the image
                //stbi_set_flip_vertically_on_load(1);
	            image = stbi_load_from_memory(imageBuffer, wB, hB, compB, 0);
	            if (image == null) {
	                throw new RuntimeException("Failed to load image: " + stbi_failure_reason());
	            }

	            w = wB.get(0);
	            h = hB.get(0);
	            comp = compB.get(0);
	}	        

	        glBindTexture(GL_TEXTURE_2D, texID);
	        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
//	        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
//	        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

	        int format;

	        if (comp == 3) {
	            if ((w & 3) != 0) {
	                glPixelStorei(GL_UNPACK_ALIGNMENT, 2 - (w & 1));
	            }
	            format = GL_RGB;
	        } else {
//	            premultiplyAlpha();
//	            glEnable(GL_BLEND);
//	            glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);

	            format = GL_RGBA;
	}

	        glTexImage2D(GL_TEXTURE_2D, 0, format, w, h, 0, format, GL_UNSIGNED_BYTE, image);

	        ByteBuffer input_pixels = image;
	        int        input_w      = w;
	        int        input_h      = h;
	        int        mipmapLevel  = 0;
	        while (1 < input_w || 1 < input_h) {
	            int output_w = Math.max(1, input_w >> 1);
	            int output_h = Math.max(1, input_h >> 1);

	            ByteBuffer output_pixels = memAlloc(output_w * output_h * comp);
	            stbir_resize_uint8_generic(
	                input_pixels, input_w, input_h, input_w * comp,
	                output_pixels, output_w, output_h, output_w * comp,
	                comp, comp == 4 ? 3 : STBIR_ALPHA_CHANNEL_NONE, STBIR_FLAG_ALPHA_PREMULTIPLIED,
	                STBIR_EDGE_CLAMP,
	                STBIR_FILTER_MITCHELL,
	                STBIR_COLORSPACE_SRGB
	            );

	            if (mipmapLevel == 0) {
	                stbi_image_free(image);
	            } else {
	                memFree(input_pixels);
	            }

	            glTexImage2D(GL_TEXTURE_2D, ++mipmapLevel, format, output_w, output_h, 0, format, GL_UNSIGNED_BYTE, output_pixels);

	            input_pixels = output_pixels;
	            input_w = output_w;
	            input_h = output_h;
	        }
	        if (mipmapLevel == 0) {
	            stbi_image_free(image);
	        } else {
	            memFree(input_pixels);
	        }

	        return texID;
	}
	
	private int sirka = 800;
	private int vyska = 600;

	void vykresliGL() {
		glLoadIdentity();
		glTranslated(0, 0, -5);
		
		glBegin(GL_QUADS);
		glTexCoord2d(0, 0);
  		glVertex3d(-1, -1, 0);
		glTexCoord2d(1, 0);
  		glVertex3d(+1, -1, 0);
		glTexCoord2d(1, 1);
  		glVertex3d(+1, +1, 0);
		glTexCoord2d(0, 1);
  		glVertex3d(-1, +1, 0);
		glEnd();

	}

	long window;
	GLFWErrorCallback errorCallback;
	GLFWKeyCallback   keyCallback;

	void spusti() {
		try {
			init();
			loop();

			glfwDestroyWindow(window);
			keyCallback.free();
		} finally {
			glfwTerminate();
			errorCallback.free();
		}
	}

	void init() {
		glfwSetErrorCallback(errorCallback = GLFWErrorCallback.createPrint(System.err));
		if (!glfwInit())
			throw new IllegalStateException("Chyba pri inicializacii GLFW!!!");

		window = glfwCreateWindow(sirka, vyska, "UGR1", NULL, NULL);
		if ( window == NULL )
			throw new RuntimeException("Chyba pri vytvoreni GLFW okna!!!");

		glfwSetKeyCallback(window, keyCallback = new GLFWKeyCallback() {
			@Override
			public void invoke(long window, int key,
					int scancode, int action, int mods) {
				if (key == GLFW_KEY_ESCAPE && action == GLFW_RELEASE)
					glfwSetWindowShouldClose(window, true);
	        
			}});

		GLFWVidMode vidmode = glfwGetVideoMode(glfwGetPrimaryMonitor());
		glfwSetWindowPos(window, (vidmode.width() - sirka) / 2, (vidmode.height() - vyska) / 2);

		glfwMakeContextCurrent(window);
		glfwSwapInterval(0);
		glfwShowWindow(window);        

		GL.createCapabilities();
	
		glEnable(GL_TEXTURE_2D);
		glBindTexture(GL_TEXTURE_2D, createTexture("pfupjs.png"));
		
	}

	private static void gluPerspective(double fov, double aspect, double zNear, double zFar) {
		double fH = Math.tan(fov*Math.PI/360.0) * zNear;
		double fW = fH * aspect;
		glFrustum( -fW, fW, -fH, fH, zNear, zFar);		
	}

	
	void loop() {
		glViewport(0,0,sirka,vyska);        

        glMatrixMode(GL_PROJECTION);
        glLoadIdentity();
		gluPerspective(45.0f, (sirka/(1.0*vyska)), 0.1f, 100.0f);	    

		glMatrixMode( GL_MODELVIEW ); 
		glLoadIdentity();

		glClearColor( 0.f, 0.f, 0.f, 1.f ); //Initialize clear color
		
//		glShadeModel(GL_SMOOTH);
//		glCullFace(GL_BACK); glEnable(GL_CULL_FACE); //Zneviditeľnenie odvrátených strán
		
		while ( !glfwWindowShouldClose(window) ) {
			glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
			vykresliGL();

			glfwSwapBuffers(window);

			glfwPollEvents();
		}
	}

	public static void main(String[] args) {
		new ugr08().spusti();
	}
}
