/src/Fill.js
import Controller from './Controller';

export default class Fill extends Controller {
    constructor(appState) {
        super(appState);
    }

    // Flood fill is actually a lot harder than it looks
    fill(x, y, targetColor) {
        let left = x, right = x;
        while (this.state.pixelEditor.getPixel(left, y) == targetColor) {
            left--;
        }
        left++;
        while (this.state.pixelEditor.getPixel(right, y) == targetColor) {
            right++;
        }
        right--;

        this.state.pixelEditor.setHLine(left, y, right - left + 1);
        for (let i = left; i <= right; i++) {
            if (this.state.pixelEditor.getPixel(i, y - 1) == targetColor) {
                this.fill(i, y - 1, targetColor);
            }
            if (this.state.pixelEditor.getPixel(i, y + 1) == targetColor) {
                this.fill(i, y + 1, targetColor);
            }
        }
    }

    down(x, y) {
        this.state.pixelEditor.pushState();
        let targetColor = this.state.pixelEditor.getPixel(x, y);
        if (targetColor == this.state.palette.color) {
            // Filling a color on top of itself is a no-op
            return;
        }
        this.fill(x, y, targetColor);
        // TODO: Calculate a bounding box as we draw and only redraw that
        this.state.pixelEditor.redraw();
        this.state.pixelEditor.refresh();
    }
    move(x, y) { }
    up(x, y) { }
}