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

public class SpaceInvadersView extends JPanel {
    private static final int WIDTH = 800;
    private static final int HEIGHT = 600;

    private static final int SPACESHIP_WIDTH = 50;
    private static final int SPACESHIP_HEIGHT = 50;

    private static final int ENEMY_WIDTH = 50;
    private static final int ENEMY_HEIGHT = 50;

    private static final int BULLET_WIDTH = 10;
    private static final int BULLET_HEIGHT = 20;

    private final SpaceInvadersModel model;

    public SpaceInvadersView(SpaceInvadersModel model) {
        this.model = model;
        setPreferredSize(new Dimension(WIDTH, HEIGHT));
    }

    private void drawHealth(Graphics g) {
        for (int i = 0; i < model.getHealth(); i++) {
            g.drawImage(model.getHeartImage(), 10 + i * 30, 10, 30, 30, this);
        }
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawImage(model.getBackgroundImage(), 0, 0, getWidth(), getHeight(), null);
        g.setColor(Color.WHITE);
        g.setFont(new Font("Arial", Font.PLAIN, 20));
        String scoreText = "Score: " + model.getScore();
        int scoreWidth = g.getFontMetrics().stringWidth(scoreText);
        g.drawString(scoreText, SpaceInvadersModel.getWidth() - scoreWidth - 10, 20);
        String level = "Level: " + model.getLevelCounter();
        g.drawString(level, 120, 30);
        g.drawImage(model.getSpaceshipImage(), model.getSpaceshipX(), model.getSpaceshipY(), SPACESHIP_WIDTH, SPACESHIP_HEIGHT, null);
        drawHealth(g);
        for (Enemy enemy : model.getEnemies()) {
            g.drawImage(model.getEnemyImage(), (int) enemy.getX(), (int) enemy.getY(), ENEMY_WIDTH, ENEMY_HEIGHT, null);
        }
        for (Bullet bullet : model.getBullets()) {
            g.drawImage(model.getBulletImage(), bullet.getX(), bullet.getY(), BULLET_WIDTH, BULLET_HEIGHT, null);
        }
        if(model.getEnemies().isEmpty()) {
            g.setFont(g.getFont().deriveFont(1.5f * g.getFont().getSize()));
            g.setFont(g.getFont().deriveFont(Font.BOLD));
            g.setColor(Color.YELLOW);
            g.drawString("Congratulations!", 275, 300);
        }
    }
}
