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

import java.util.BitSet;

import javafx.application.Platform;
import javafx.scene.Group;
import javafx.scene.image.ImageView;
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.Render;
import nz.ac.massey.javaecs.examples.Components.Sprite;
import nz.ac.massey.javaecs.examples.Components.Vec2D;
/*
 * This render system is different from demo 1, as its main functionality is provided directly by the program, not as an entity.
*/
public class RenderSystem extends ECSSystem {
    Engine gameEngine;
    Group renderGroup;
    Thread renderThread;
    double renderScale;
    int screenX = 512;
    int screenY = 512;

    public RenderSystem(Engine gameEngine, double renderScale){
        this.gameEngine = gameEngine;
        // Set registrations
        registrationSet = new BitSet();
        registrationSet.set(gameEngine.getComponentIndex(Render.class));
        this.renderScale = renderScale;
    }
    public void init(Group renderGroup) throws Exception {
        this.renderGroup = renderGroup;        
    }

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

    @Override
    public void update(double dt) {
        Group frame = new Group();
        for (Entity entity : entities) {
            Vec2D pos = (Vec2D)gameEngine.getComponentData(entity, Vec2D.class);
            if (((Render)gameEngine.getComponentData(entity, Render.class)).renderType == Sprite.class){
                // Render the sprite
                Sprite sprite = (Sprite)gameEngine.getComponentData(entity, Sprite.class);
                ImageView spriteRender = new ImageView(sprite.sprite);
                spriteRender.setX(pos.x);
                spriteRender.setY(pos.y);
                spriteRender.setFitWidth(sprite.width);
                spriteRender.setFitHeight(sprite.height);
                frame.getChildren().add(spriteRender);
            }
        }
        
        // Must be run by the UI thread, not the main thread.
        // This dispatches the operation run() to the UI.
        Platform.runLater(new Runnable(){
            @Override
            public void run() {
                renderGroup.getChildren().clear();
                renderGroup.getChildren().add(frame);
            }
        });
    }
}
