package se.urmo.game.main;

import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

import javax.swing.JFrame;

@Slf4j
public class Game implements Runnable {
    public final static int FPS_SET = 120;
    public final static int UPS_SET = 200;
    private final static double timePerFrame = 1000000000.0 / FPS_SET;
    private final static double timePerUpdate = 1000000000.0 / UPS_SET;


    @Getter
    private final GameStateManager gameStateManager;
    private Thread gameThread;
    private final JFrame window = new JFrame();
    @Getter
    private final GamePanel gamePanel;

    public Game() {
        this.gameStateManager = new GameStateManager();
        this.gamePanel = new GamePanel(this, gameStateManager);
    }

    public void start() {
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        window.setResizable(false);
        window.setTitle("PacMan");


        window.add(gamePanel);

        window.pack();

        window.setLocationRelativeTo(null);
        window.setVisible(true);

        this.gameThread = new Thread(this);
        gameThread.start();
    }
    @Override
    public void run() {
        long previousTime = System.nanoTime();

        int frames = 0;
        int updates = 0;
        long lastCheck = System.currentTimeMillis();

        double deltaU = 0;
        double deltaF = 0;

        while (gameThread !=null && gameThread.isAlive()) {
            long currentTime = System.nanoTime();
            deltaU += (currentTime - previousTime) / timePerUpdate;
            deltaF += (currentTime - previousTime) / timePerFrame;

            previousTime = currentTime;

            if (deltaU >= 1) {
                gameStateManager.update();
                updates++;
                deltaU--;
            }

            if (deltaF >= 1) {
                gamePanel.repaint(); // triggers JPanel paintComponent
                frames++;
                deltaF--;
            }

            if (System.currentTimeMillis() - lastCheck >= 1000) {
                lastCheck = System.currentTimeMillis();
                log.debug("FPS: " + frames + " | UPS: " + updates);
                frames = 0;
                updates = 0;
            }
        }
    }
}
