package org.academiadecodigo.enuminatti.paint.painter;

import org.academiadecodigo.enuminatti.paint.grid.*;
import org.academiadecodigo.simplegraphics.graphics.Color;
import org.academiadecodigo.simplegraphics.graphics.Rectangle;

import java.util.ArrayList;

/**
 * MIT License
 * (c) 2017 Ricardo Constantino
 */

public class SimpleGraphics implements Painter {
    private int delay;
    private Cursor cursor;
    private static final int CELLSIZE = 30;
    private static final int PADDING = 10;
    private ArrayList<SimpleRectangle> cells;

    SimpleGraphics(int delay, Grid grid) {
        this.delay = delay;
        this.cursor = grid.getCursor();

        cells = new ArrayList<>();
        for (Cell cell : grid.getCells()) {
            cells.add(new SimpleRectangle(cell));
        }
    }

    @Override
    public void paint() throws InterruptedException {
        for (SimpleRectangle cell : cells) {
            cell.draw();
        }

        Thread.sleep(delay);
    }

    private enum SimpleColor {
        NOCOLOR,
        BLACK,
        GREEN,
        RED,
        BLUE;

        public Color getColor() {
            switch (this) {
                case GREEN:
                    return Color.GREEN;
                case RED:
                    return Color.RED;
                case BLUE:
                    return Color.BLUE;
                case BLACK:
                default:
                    return Color.BLACK;
            }
        }

        public static SimpleColor convert(Swatch swatch) {
            return SimpleColor.values()[swatch.ordinal()];
        }
    }

    private class SimpleRectangle {
        private Cell cell;
        private Rectangle rectangle;
        private SimpleColor color;

        SimpleRectangle(Cell cell) {
            this.cell = cell;
            Position cellPos = cell.getPosition();
            rectangle = new Rectangle(
                    PADDING + cellPos.getCol() * CELLSIZE,
                    PADDING + cellPos.getRow() * CELLSIZE,
                    CELLSIZE, CELLSIZE);
            color = SimpleColor.NOCOLOR;
            rectangle.setColor(color.getColor());
            draw();
        }

        void draw() {
            SimpleColor newCellColor = color;

            if (cell.getPosition().equals(cursor.getPos())) {
                if (cell.isPainted()) {
                    rectangle.setColor(Color.YELLOW);
                } else {
                    rectangle.setColor(SimpleColor.convert(cursor.getCurrentSwatch()).getColor());
                }
                rectangle.fill();
                return;
            }

            newCellColor = SimpleColor.convert(cell.getCurrentSwatch());

            rectangle.setColor(newCellColor.getColor());
            if (newCellColor == SimpleColor.NOCOLOR) {
                rectangle.draw();
            } else {
                rectangle.fill();
            }
            color = newCellColor;
        }
    }

}
