package nz.ac.massey.javaecs.examples.Systems;

import java.util.BitSet;

import javafx.application.Platform;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.stage.Stage;
import nz.ac.massey.javaecs.ECSSystem;
import nz.ac.massey.javaecs.Engine;
import nz.ac.massey.javaecs.Entity;
import nz.ac.massey.javaecs.examples.Components.Input;


/**
 * The control system creates a handler for input in the world stage.
 * It then passes input events as they occur to the Input component
 * The ControlSystem reads this input every frame update and enacts
 * on the player controller
 */
public class ControlSystem extends ECSSystem {
    Engine gameEngine;
    Entity inputEntity;

    public ControlSystem(Engine gamEngine){
        this.gameEngine = gamEngine;
        registrationSet = new BitSet();
        registrationSet.set(gameEngine.getComponentIndex(Input.class));
    }

    public void init(Stage world) {
        // use a single entity to control inputs, it is present in the world stage
        // and is responsible for collecting & passing data
        inputEntity = entities.iterator().next();

        // Add an event handler to the stage. This
        Platform.runLater(new Runnable(){
            @Override
            public void run() {
                world.addEventHandler(KeyEvent.KEY_PRESSED, (key) -> {
                    if(key.getCode()==KeyCode.W) {
                        updateKeyPress(0);
                        System.err.println("W pressed");
                    }
                    else if(key.getCode()==KeyCode.S) {
                        updateKeyPress(1);
                        System.err.println("S pressed");
                    }
                    else if(key.getCode()==KeyCode.A) {
                        updateKeyPress(2);
                        System.err.println("A pressed");
                    }
                    else if(key.getCode()==KeyCode.D) {
                        updateKeyPress(3);
                        System.err.println("D pressed");
                    }
                });
            }
        });
    }

    @Override
    public void update(double dt) {
        //Input inputUpdate = (Input)gameEngine.getComponentData(inputEntity, Input.class);
        // TODO Auto-generated method stub
        
    }

    // Updates the input's keypressed state
    protected void updateKeyPress(int dir){
        Input inputUpdate = (Input)gameEngine.getComponentData(inputEntity, Input.class);
        inputUpdate.input.set(dir);
    }

    @Override
    public void init() throws Exception {
        // TODO Auto-generated method stub
        
    }
    
}
