package eu.midnightdust.yaytris.ui;

import eu.midnightdust.yaytris.Tetris;
import eu.midnightdust.yaytris.game.Tetromino;
import eu.midnightdust.yaytris.game.TetrominoShape;
import eu.midnightdust.yaytris.util.FileUtil;

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

import static eu.midnightdust.yaytris.game.TetrominoShape.T;

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

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

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

        TetrominoShape nextShape = Tetris.getSpace().getNextShape();
        for (int y = 0; y < nextShape.getBoundary().length; y++) {
            for (int x = 0; x < nextShape.getBoundary()[0].length; x++) {
                Color color = nextShape.getBoundary()[y][x] == 0 ? null : nextShape.getColor(); // 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) / 4);
                int startX = x * blockSize + getInsets().left + ((blockSize / 2) * (4 - nextShape.getBoundary()[0].length));
                graphics.drawImage(texture, startX, 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(startX, y*blockSize + getInsets().top, blockSize, blockSize);
            }
        }
    }

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