package eu.midnightdust.yaytris.ui;

import eu.midnightdust.yaytris.Tetris;
import eu.midnightdust.yaytris.util.FileUtil;

import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;

public class GameCanvas extends JPanel {
    final TetrisUI ui;
    final BufferedImage texture;

    GameCanvas(TetrisUI ui) {
        this.ui = ui;
        this.texture = FileUtil.loadImage("/textures/tetromino.png");
    }

    public void paintComponent(Graphics graphics) {
        super.paintComponent(graphics);
        if (graphics == null) return;

        for (int y = 0; y < Tetris.getSpace().getMapHeight(); y++) {
            for (int x = 0; x < Tetris.getSpace().getMapWidth(); x++) {
                Color color = Tetris.getSpace().getGameMapWithTetromino()[y][x]; // Get the color of the blob at these coordinates
                if (color == null) continue; // Ignore empty cells
                int blockSize = (int) Math.ceil((float) (this.getWidth() - this.getInsets().left - this.getInsets().right) / Tetris.getSpace().getMapWidth());
                graphics.drawImage(texture, x*blockSize +getInsets().left, y*blockSize + getInsets().top, blockSize, blockSize, color, this); // Draw out (grayscale) texture
                graphics.setColor(withAlpha(color, 120)); // Overlay the texture with the blobs color
                graphics.fillRect(x*blockSize +getInsets().left, y*blockSize + getInsets().top, blockSize, blockSize);
            }
        }
    }

    public static Color withAlpha(Color color, int alpha) {
        return new Color(color.getRed(), color.getGreen(), color.getBlue(), alpha);
    }
}
