package org.artisanlogiciel.games.maze;

import org.artisanlogiciel.graphics.Drawing;
import org.artisanlogiciel.graphics.DrawingLine;

import java.awt.*;

public class DrawingGenerator {

    LabyModel model;

    public DrawingGenerator(LabyModel model) {
        this.model = model;
    }

    void addWallInDrawing(int pX, int pY, Drawing d) {
        short walls = model.getWalls(pX, pY);
        short wdrawn = 0;
        // todo
        int w = 2;
        int h = 2;
        int ox = 0;
        int oy = 0;

        int x = ox + (int) (pX * w);
        int y = oy + (int) (pY * h);
        DrawingLine dl = new DrawingLine();
        // order matters since all points are linked
        if ((pY == 0) && LabyModel.isFlagSet(walls, Brick.UP)) {
            dl.addPoint(new Point(x, y));
            dl.addPoint(new Point(x + (int) w, y));
            wdrawn |= Brick.UP;
        }
        if (LabyModel.isFlagSet(walls, Brick.RIGHT)) {
            if (!LabyModel.isFlagSet(wdrawn, Brick.UP)) {
                dl.addPoint(new Point(x + (int) w, y));
            }
            dl.addPoint(new Point(x + (int) w, y + (int) h));
            wdrawn |= Brick.RIGHT;
        }
        if (LabyModel.isFlagSet(walls, Brick.DOWN)) {
            if (!LabyModel.isFlagSet(wdrawn, Brick.RIGHT)) {
                if (wdrawn != 0) {
                    d.addLine(dl);
                    dl = new DrawingLine();
                }
                dl.addPoint(new Point(x + (int) w, y + (int) h));
            }
            dl.addPoint(new Point(x, y + (int) h));
            wdrawn |= Brick.DOWN;
        }
        if ((pX == 0) && LabyModel.isFlagSet(walls, Brick.LEFT)) {
            if (!LabyModel.isFlagSet(wdrawn, Brick.DOWN)) {
                if (wdrawn != 0) {
                    d.addLine(dl);
                    dl = new DrawingLine();
                }
                dl.addPoint(new Point(x, y + (int) h));
            }
            dl.addPoint(new Point(x, y));
            wdrawn |= Brick.LEFT;
        }
        if (wdrawn != 0) {
            d.addLine(dl);
        }
    }

    public Drawing createDrawing() {
        Drawing d = new Drawing();
        {
            // draw all walls within clip bounds horiz first then lines
            for (int y = 0; y < model.getHeight(); y++) {
                for (int x = 0; x < model.getWidth(); x++) {
                    addWallInDrawing(x, y, d);
                }
            }
        }
        return d;
    }
}
