package se.urmo.game.main;

import lombok.extern.slf4j.Slf4j;
import se.urmo.game.entities.collectibles.Fruit;
import se.urmo.game.entities.pacman.PacMan;
import se.urmo.game.state.PlayingState;
import se.urmo.game.util.FruitType;

import java.awt.Graphics;

@Slf4j
public class FruitManager {
    private final LevelManager levelManager;
    private Fruit activeFruit;

    public FruitManager(LevelManager levelManager) {
        this.levelManager = levelManager;
    }

    public void dotEaten(int dotsEaten) {
        dotsEaten++;
        if (dotsEaten == 10 || dotsEaten == 170) {
            spawnFruit(levelManager.getCurrentLevel().getLevel());
        }
    }

    private void spawnFruit(int level) {
        FruitType type = FruitType.forLevel(level);

        activeFruit = new Fruit(type);
    }

    public void update(PacMan pacman, PlayingState playingState) {
        if (activeFruit != null) {
            if (activeFruit.isExpired()) {
                activeFruit = null;
                return;
            }

            if (activeFruit.collidesWith(pacman)) {
                playingState.setScore(activeFruit.getScore());
                activeFruit = null;
            }
        }
    }

    public void draw(Graphics g) {
        if (activeFruit != null) {
            activeFruit.draw(g);
        }
    }

    public void reset() {
        activeFruit = null;
    }
}
