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

import java.util.BitSet;

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.Control;
import nz.ac.massey.javaecs.examples.Components.Input;
import nz.ac.massey.javaecs.examples.Components.Sprite;
import nz.ac.massey.javaecs.examples.Components.Vec2D;

public class PlayerSystem extends ECSSystem{
    Engine gameEngine;
    Entity inputEntity; // Entity which recieves event data


    public PlayerSystem(Engine gameEngine){
        this.gameEngine = gameEngine;
        registrationSet = new BitSet();
        registrationSet.set(gameEngine.getComponentIndex(Control.class));
    }

    public void init(Entity inputEntity){
        this.inputEntity = inputEntity;
    }

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

    @Override
    public void update(double dt) {
        int state = ((Input)gameEngine.getComponentData(inputEntity, Input.class)).input.get();
        // The value of the input may change before control leaves here; sychronisation isn't
        // hugely important through this section. So we can just ignore the change
        for (Entity entity : entities) {
            Vec2D pos = (Vec2D)gameEngine.getComponentData(entity, Vec2D.class);
            Sprite sprite = (Sprite)gameEngine.getComponentData(entity, Sprite.class);
            if (state == 0){ // W
                pos.y -= sprite.height/2;
            }
            else if (state == 1){ // S
                pos.y += sprite.height/2;
            }
            else if (state == 2){ // A
                pos.x -= sprite.width/2;
            }
            else if (state == 3){ // D
                pos.x += sprite.width/2;
            }
        }
        // Finally, unset the state 
        ((Input)gameEngine.getComponentData(inputEntity, Input.class)).input.set(-1); // Unset the state, it has been handled        
    }
    
}
