package ru.cdmlex.jtest;

import java.awt.*;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.util.concurrent.atomic.AtomicBoolean;
import java.awt.image.BufferedImage;
import static ru.cdmlex.jtest.Constants.*;

public class CanvasJGame extends Canvas implements JGame, Runnable {
	private Thread gameThread;
	private AtomicBoolean running;
	private Input input;
	private Scene scene;
	private int wx;
	public CanvasJGame(Dimension screenSize, int wx) {
		this.wx = wx;
        running = new AtomicBoolean(false);
        setSize(screenSize);
        initInput();
        initFocusListener();
    }
	
	private void initInput() {
        input = new Input();
        addKeyListener(input);
    }
	
    private void initFocusListener() {
        addFocusListener(	new FocusListener() {
            @Override
            public void focusGained(FocusEvent event) {
                start();
            }
            @Override
            public void focusLost(FocusEvent event) {
                pause();
            }
        });
    }
	
    @Override
    public void start() {
        if (running.compareAndSet(false, true)) {
            gameThread = new Thread(this);
            gameThread.start();
        }
    }
	
	@Override
    public void pause() {
        if (running.compareAndSet(true, false)) {
            try {
                gameThread.join();
            } catch (InterruptedException exception) {
                throw new RuntimeException(exception);
            }
        }
    }
	
    @Override
    public Dimension getScreenSize() {
        return getSize();
    }
    
	@Override
    public Input getInput() {
        return input;
    }
    
	@Override
    public void setScene(Scene scene) {
        this.scene = scene;
    }
    
	@Override
    public void run() {
        long previousIterationTime = System.nanoTime();
		Graphics2D g = (Graphics2D)getBufferStrategy().getDrawGraphics();
		
		BufferedImage buffer = new BufferedImage(160, 144, BufferedImage.TYPE_INT_ARGB);
		Graphics2D g2d = buffer.createGraphics();
	
        while (running.get()) {
            if (scene == null) {
                continue;
            }
            long now = System.nanoTime();
            long nanosPassed = now - previousIterationTime;
            previousIterationTime = now;
            
            scene.update(nanosPassed);
            scene.draw(g2d);
			//g.drawImage(buffer,0,0,this);
			g.drawImage(buffer,0,0,160*wx,144*wx,0,0,160,144,this);
            getBufferStrategy().show();
        }
    }
	
}