package engine;

import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferStrategy;

import javax.swing.JFrame;

import _texture.loader.Textures;
import utils.Runner;
import utils.Utils;

final class SplashScreen extends Canvas {
	private static final long serialVersionUID = 1337;
	
		private static Graphics g;
		private static Graphics2D g2d;
		private static BufferStrategy bs;
		public static SplashScreen splash = new SplashScreen();
		public static JFrame splashFrame;
		
		public static final void init(){
			splashFrame = new JFrame("\"Nihilne\" ---- " + Game.version);
			splashFrame.setLocation(java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds().width / 2 - splashFrame.getWidth() / 2, 
			java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds().height / 2 - splashFrame.getHeight() / 2);
			splashFrame.setAlwaysOnTop(true);
			splashFrame.setUndecorated(true);
			splashFrame.setSize(600, 240);
			splashFrame.add(splash);
			splash.setVisible(true);
			splashFrame.setVisible(true);
			splashFrame.setLocationRelativeTo(null);
		}
		
		private static volatile boolean rendering;
		public static final Runner splashRender = new Runner(() -> {
			while(Game.init){
				if(rendering) return; rendering = true;
				if(splash == null || splashFrame == null) return;
				try{ if (bs == null) splash.createBufferStrategy(3); bs = splash.getBufferStrategy(); g = bs.getDrawGraphics(); 
				if (!(g == null)) g2d = (Graphics2D) g.create();
				if(g == null || g2d == null || bs == null) return;
				g2d.drawImage(Textures.splashSheet[1], 0, 0, null); g2d.setFont(fonts.fonts.Gregorian20);
				g2d.setColor(Color.red); g2d.drawString(Game.version, splashFrame.getWidth() / 17, (int)(splashFrame.getHeight() / 1.1f));
				g.setColor(Color.green); g.drawString(Utils.OS, (int)(splashFrame.getWidth() / 17), (int)(splashFrame.getHeight() / 1.3f));
				bs.show(); g2d.dispose(); g.dispose();
				} catch (IllegalStateException ise) { ise.printStackTrace();
				} catch (ClassCastException cce) {
				} catch (NullPointerException npe){
				} catch (Exception e){}
				
				rendering = false;
			}
		});
		
		public static final void cleanUp(){
			try{ splash.setVisible(false); splashFrame.setVisible(false);
			splashFrame.dispose(); bs.dispose(); g.dispose(); g2d.dispose(); bs=null; g=g2d=null; splash = null; splashFrame = null; System.gc();
			} catch (NullPointerException npe){ splashFrame.setVisible(false); npe.printStackTrace(); }
		}
	
}
