import processing.core.PApplet;
import java.awt.Point;
import java.util.ArrayList;
import java.util.List;

public class GameLoop {
    int activePlayer = 0;

    private final int CAM = 1;                  // Kamera-ID (0 für Webcam, 1 für andere Cams)
    private final int EXP = -9;                 // Belichtungszeit (idealerweise: 0)
    private final int FPS = 20;                 // FPS
    private final int THV = 245;                // Threshold

    ImgAnalyzer tracker;
    CamPuffer camPuffer;

    GraphicsProgram graphics;

    GameLogic gl;

    Player player1;
    Player player2;

    public GameLoop(){
        player1 = new Player(0, "192.168.1.1", 9000);
        player2 = new Player(1, "192.168.1.2", 9000);

        camPuffer = new CamPuffer(CAM, EXP, FPS, THV);
        Thread pufferThread = new Thread(camPuffer);
        pufferThread.start();

        tracker = new ImgAnalyzer(camPuffer, THV);
        Thread trackerThread = new Thread(tracker::run);
        trackerThread.start();

        /*graphics = new GraphicsProgram(player1, player2);
        String[] args = {"GraphicsProgram"};
        PApplet.runSketch(args, graphics);


        gl = new GameLogic();
        String[] args_ = {"GameLogic"};
        PApplet.runSketch(args_, gl); */

        run();
    }

    private void run(){
        while(true){
            //communicate();

            Point p1 = tracker.getP1();
            //System.out.println("Player 1 is at " + p1.x + " and " + p1.y);
            Point p2 = tracker.getP2();
            //System.out.println("Player 2 is at " + p2.x + " and " + p2.y);

            /*player1.setKoords(p1.x, p1.y);
            player2.setKoords(p2.x, p2.y);

            if(gl.doCheckExtern(player2.getTrail(), p1)){ //Check Position von P1 mit Spur von P2
                System.out.println("Spieler 1 hat verloren");
                break;
            }

            if(gl.doCheckExtern(player1.getTrail(), p2)){ //Check Position von P2 mit Spur von P1
                System.out.println("Spieler 2 hat verloren");
                break;
            } */

            //draw();

            try{
                wait(50);
            }
            catch (Exception e){
            }
        }
    }

    private void communicate() {
        //offen für Auto Kommunikation
    }

    /*private List<Point> track(){
        Point p1 = tracker.getP1();
        Point p2 = tracker.getP2();
        System.out.println(p1.x);

        player1.setKoords(p1.x, p1.y);
        player2.setKoords(p2.x, p2.y);

        List<Point> output = new ArrayList<>();
        output.add(0, p1);
        output.add(1, p2);
        return output;
    }*/

    private void draw(){
    }
}