package model;

import util.Position;
import util.TargetStrategy;

import java.util.*;

public class FirefighterBehavior extends FFBehavior implements TangibleBehavior<ModelElement>,RemoverBehavior<ModelElement> {
    List<ModelElement> obstacles=List.of(ModelElement.MOUNTAIN);
    ModelElement removedElement=ModelElement.FIRE;
    TargetStrategy targetStrategy=new TargetStrategy();

    public FirefighterBehavior(ModelElement modelElement) {
        super(modelElement);
    }


    @Override
    public List<Position> getNext(BoardData boardData) {
        List<Position> firefighterPositions = boardData.getPositions().get(element.ordinal());
        List<Position> firePositions = new ArrayList<>(List.copyOf(boardData.getPositions().get(ModelElement.FIRE.ordinal())));
        List<Position> firefighterNewPositions = new ArrayList<>();
        Map<Position,List<Position>> neigbours=legalNeighbors(boardData);
        for (Position firefighterPosition : firefighterPositions) {
            Position newFirefighterPosition = targetStrategy.neighborClosestToFire(firefighterPosition,firePositions, neigbours);
            firefighterNewPositions.add(newFirefighterPosition);
            firePositions.remove(newFirefighterPosition);
            firePositions.remove(boardData.getNeighbors().get(newFirefighterPosition));
        }
        return firefighterNewPositions;
    }
    public List<Position> remove(BoardData boardData,Position p){
        List<Position> firePositions = boardData.getPositions().get(getElementToRemove().ordinal());
        List<Position> neighborFirePositions = boardData.getNeighbors().get(p).stream()
                .filter(firePositions::contains).toList();
        removePartial(boardData,p);
        for (Position firePosition : neighborFirePositions)
            removePartial(boardData,firePosition);
        return neighborFirePositions;
    }


    @Override
    public List<ModelElement> getObstacles() {
        return obstacles;
    }

    @Override
    public void removePartial(BoardData boardData,Position p) {
        List<Position> firePositions = boardData.getPositions().get(getElementToRemove().ordinal());
        firePositions.remove(p);
    }

    @Override
    public Map<Position, List<Position>> legalNeighbors(BoardData boardData) {
        Map<Position,List<Position>> neigbours= Map.copyOf(super.legalNeighbors(boardData));
        for (Map.Entry<Position,List<Position>> entry: neigbours.entrySet()) {
            for (ModelElement e:getObstacles()) {
                entry.getValue().removeAll(boardData.getPositions().get(e.ordinal()));
            }
        }
        return neigbours;
    }

    @Override
    public ModelElement getElementToRemove() {
        return removedElement;
    }
}