package school_project.Utils;

import javafx.scene.Node;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Paint;
import javafx.scene.shape.Rectangle;
import school_project.*;

import java.io.FileInputStream;
import java.io.FileNotFoundException;

public class MatrixShape extends GridPane {
    public Shape shape;
    public Vec2 boundary_size = new Vec2();
    private Paint color;
    public MatrixShape(Shape shape) {
        super();
        this.shape = shape;
        if(shape instanceof Piece){
            Piece p = (Piece) shape;
            color = p.getColor();
        }

        update();

        setHgap(GameUI.SPACE_SIZE);
        setVgap(GameUI.SPACE_SIZE);
    }

    public void update(){
        getChildren().clear();
        boolean[][] shape_matrix = shape.getShape();
        for (int i = 0; i < shape_matrix.length; i++) {
            for (int j = 0; j < shape_matrix[i].length; j++) {
                Node _cell;
                if(shape_matrix[i][j]){
                    if(shape instanceof Piece){
                        Piece p = (Piece) shape;
                        _cell = new Rectangle(GameUI.SEGMENT_SIZE, GameUI.SEGMENT_SIZE);
                        ((Rectangle) _cell).setFill(color);
                    }else{
                        try {
                          _cell = new ImageView(new Image(new FileInputStream(Controller.class.getResource("tile.png").getFile())));
                        } catch (FileNotFoundException e) {
                            throw new RuntimeException(e);
                        }
                    }
                }
                else{
                    _cell = new Pane();
                    ((Pane) _cell).setPrefSize(GameUI.SEGMENT_SIZE, GameUI.SEGMENT_SIZE);
                }
                add(_cell, j, i);
            }
        }
        boundary_size = new Vec2((GameUI.SEGMENT_SIZE + GameUI.SPACE_SIZE) * shape.getWidth(), (GameUI.SEGMENT_SIZE + GameUI.SPACE_SIZE) * shape.getHeight());
    }
    public void setColor(Paint p) {
        color = p;
    }
}
