package com.javarush.games.minesweeper;

import com.javarush.engine.cell.Game;
import com.javarush.engine.cell.*;

import java.util.ArrayList;
import java.util.List;

import static com.javarush.engine.cell.Color.RED;
import static com.javarush.engine.cell.Color.YELLOW;

public class MinesweeperGame extends Game {
    private static final int SIDE = 9;
    private static final Color color = YELLOW;
    private int countMinesOnField;
    private static final String MINE = "\uD83D\uDCA3";
    private static final String FLAG = "\uD83D\uDEA9";
    private int countFlags;

    public void initialize() {
        setScreenSize(SIDE, SIDE);
        createGame();
    }

    private GameObject[][] gameField = new GameObject[SIDE][SIDE];

    private List<GameObject> getNeighbors(GameObject gameObject) {
        List<GameObject> neighbors = new ArrayList<>();
        int x = gameObject.x;
        int y = gameObject.y;
        for (int i = x - 1; i <= x + 1; i++) {
            for (int j = y - 1; j <= y + 1; j++) {
                if ((i != x || j != y) && (i >= 0 && j >= 0 && i < SIDE && j < SIDE)) {
                    neighbors.add(gameField[i][j]);
                }
            }
        }
        return neighbors;
    }

    public void onMouseLeftClick(int x, int y) {
        openTile(x, y);
    }

    private void openTile(int x, int y) {
        gameField[x][y].isOpen = true;
        setCellColor(x, y, RED);
        if (gameField[x][y].isMine) {
            setCellValue(x, y, MINE);
        } else if (gameField[x][y].countMineNeighbors == 0) {
            for (GameObject gameObject : getNeighbors(gameField[x][y])) {
                if (gameObject.isOpen)
                    setCellValue(x, y, "");
                    openTile(gameObject.x, gameObject.y);
                    gameField[x][y].isOpen = true;
            }
        } else {
            setCellNumber(x, y, gameField[x][y].countMineNeighbors);
        }
    }

    private void countMineNeighbors() {

        for (int i = 0; i < SIDE; i++) {
            for (int j = 0; j < SIDE; j++) {
                int tmpCount = 0;
                if (!gameField[j][i].isMine) {
                    for (GameObject gmo : getNeighbors(gameField[i][j])) {
                        if (gmo.isMine) tmpCount++;
                    }
                    gameField[j][i].countMineNeighbors = tmpCount;
                }
            }
        }
    }

    private void createGame() {
        for (int x = 0; x < gameField.length; x++) {
            for (int y = 0; y < gameField[x].length; y++) {
                boolean mine = false;
                if (getRandomNumber(10) < 1) {
                    mine = true;
                    countMinesOnField++;
                }
                gameField[x][y] = new GameObject(y, x, mine);
                setCellColor(x, y, color);

            }
        }
        countMineNeighbors();
        countFlags = countMinesOnField;
    }
}