package org.academiadecodigo.enuminatti.paint.painter;

import com.googlecode.lanterna.TerminalFacade;
import com.googlecode.lanterna.screen.Screen;
import com.googlecode.lanterna.terminal.Terminal;
import org.academiadecodigo.enuminatti.paint.grid.Cell;
import org.academiadecodigo.enuminatti.paint.grid.Cursor;
import org.academiadecodigo.enuminatti.paint.grid.Grid;
import org.academiadecodigo.enuminatti.paint.grid.Position;

import java.util.ArrayList;

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

public class Lanterna implements Painter {
    private int delay;
    private Cursor cursor;
    private ArrayList<LanternaChar> cells;
    private static Screen screen;

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

        // create the GUI
        screen = TerminalFacade.createScreen();

        // set the grid size
        screen.getTerminal().setCursorVisible(false); // Not Working
        screen.getTerminal().getTerminalSize().setColumns(grid.getCols());
        screen.getTerminal().getTerminalSize().setRows(grid.getRows());

        // display the grid
        screen.startScreen();

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

    @Override
    public void paint() throws InterruptedException {
        for (LanternaChar cell : cells) {
            cell.draw();
        }
        screen.refresh();
        Thread.sleep(delay);
    }

    private class LanternaChar {
        private Cell cell;
        private Terminal.Color color;

        LanternaChar(Cell cell) {
            this.cell = cell;
            draw();
        }

        void draw() {
            Position cellPos = cell.getPosition();
            Terminal.Color newColor = color;

            if (cell.getPosition().equals(cursor.getPos())) {
                if (cell.isPainted()) {
                    newColor = Terminal.Color.YELLOW;
                } else {
                    newColor = Terminal.Color.BLUE;
                }
            } else {
                if (cell.isPainted()) {
                    newColor = Terminal.Color.BLACK;
                } else {
                    newColor = Terminal.Color.DEFAULT;
                }
            }
            if (!newColor.equals(color)) {
                color = newColor;
                screen.putString(cellPos.getCol(), cellPos.getRow(), " ",
                        color, color);
            }
        }
    }
}
