package ca.recrown.islandsurvivalcraft.utilities.floodfill;


import java.util.HashSet;
import java.util.LinkedList;

import ca.recrown.islandsurvivalcraft.utilities.datatypes.Point2;

public class Flooder {
    private final Point2 start;
    private final Floodable floodable;

    public Flooder(Point2 start, Floodable floodable) {
        this.start = start;
        this.floodable = floodable;
    }

    public Flooder(int xStart, int yStart, Floodable floodable) {
        this(new Point2(xStart, yStart),  floodable);
    }

    public void start() {
        HashSet<Point2> checked = new HashSet<>();
        LinkedList<Point2> queue = new LinkedList<>();

        if (!checked.add(start)) return;
        if (!floodable.flood(start)) return;
        queue.add(start);
        while (!queue.isEmpty()) {
            Point2 p = queue.pop();

            Point2 pE = new Point2(p.x + 1, p.y);
            if (checked.add(pE) && floodable.flood(pE)) queue.add(pE);

            Point2 pW = new Point2(p.x - 1, p.y);
            if (checked.add(pW) && floodable.flood(pW)) queue.add(pW);

            Point2 pN = new Point2(p.x, p.y + 1);
            if (checked.add(pN) && floodable.flood(pN)) queue.add(pN);

            Point2 pS = new Point2(p.x, p.y - 1);
            if (checked.add(pS) && floodable.flood(pS)) queue.add(pS);
        }
    }
}