using System;
using System.Collections.Generic;
using System.Text;
using System.Timers;

namespace MyMineSwapper {
	public class Square {
		public Square() {
			this.type = 'X';
		}

		public char type;
	}

	public class MineTable {
		public void GenerateTable(int width, int height, int mineCount) {
			this.height = height;
			this.width = width;
			this.mineCount = mineCount;
			this.flagCount = 0;
			this.table = new Square[this.height, this.width];
			this.screen = new Square[this.height, this.width];
			this.InitializeTables();

			Random randomObject = new Random();
			int counter = 0;
			while (counter < mineCount) {
				int i = randomObject.Next(0, height);
				int j = randomObject.Next(0, width);
				if (this.table[i, j].type != '*') {
					this.table[i, j].type = '*';
					++counter;
				}
			}

			this.CalculateNeighboursOfMines();
		}

		private char IntToChar(int n) {
			return n.ToString()[0];
		}

		private void CalculateNeighboursOfMines() {
			for (int i = 0; i < this.height; ++i) {
				for (int j = 0; j < this.width; ++j) {
					if (this.table[i, j].type != '*') {
						int counter = 0;
						// north
						if (i > 0 && this.table[i - 1, j].type == '*') {
							++counter;
						}
						// north-east
						if (i > 0 && j < this.width - 1 && this.table[i - 1, j + 1].type == '*') {
							++counter;
						}
						// east
						if (j < this.width - 1 && this.table[i, j + 1].type == '*') {
							++counter;
						}
						// south-east
						if (i < this.height - 1 && j < this.width - 1 && this.table[i + 1, j + 1].type == '*') {
							++counter;
						}
						// south
						if (i < this.height - 1 && this.table[i + 1, j].type == '*') {
							++counter;
						}
						// south-west
						if (i < this.height - 1 && j > 0 && this.table[i + 1, j - 1].type == '*') {
							++counter;
						}
						// west
						if (j > 0 && this.table[i, j - 1].type == '*') {
							++counter;
						}
						// north-west
						if (i > 0 && j > 0 && this.table[i - 1, j - 1].type == '*') {
							++counter;
						}
						this.table[i, j].type = this.IntToChar(counter);
					}
				}
			}
		}

		private void InitializeTables() {
			for (int i = 0; i < this.height; ++i) {
				for (int j = 0; j < this.width; ++j) {
					this.screen[i, j] = new Square();
					this.table[i, j] = new Square();
				}
			}
		}

		public void Run() {
			Console.SetWindowSize(this.width, this.height + 1);

			bool exit = false;
			int left = 0;
			int top = 1;
			int result;
			this.PrintScreen(left, top);
			while (exit == false) {
				
				ConsoleKeyInfo consoleKey = Console.ReadKey();

				// X
				if (consoleKey.Key == ConsoleKey.X && this.GetPositiveNumberOfMine(this.screen[top - 1, left].type, out result) == true) {
					this.ShowHidedNeighbours(top - 1, left, result, out exit);
				} else {
					// arrows
					if (consoleKey.Key == ConsoleKey.LeftArrow && left > 0) {
						--left;
					} else if (consoleKey.Key == ConsoleKey.RightArrow && left < this.width - 1) {
						++left;
					} else if (consoleKey.Key == ConsoleKey.UpArrow && top > 1) {
						--top;
					} else if (consoleKey.Key == ConsoleKey.DownArrow && top < this.height) {
						++top;
					}
						// space
					else if (consoleKey.Key == ConsoleKey.Spacebar && screen[top - 1, left].type != '>' && screen[top - 1, left].type != '?') {
						if (this.table[top - 1, left].type == '0') {
							this.screen[top - 1, left].type = ' ';
							this.ShowNeighbours(top - 1, left);
						} else if (this.table[top - 1, left].type == '*') {
							this.screen[top - 1, left].type = this.table[top - 1, left].type;
							exit = true;
						} else {
							this.screen[top - 1, left].type = this.table[top - 1, left].type;
						}
					}
						// m
					else if (consoleKey.Key == ConsoleKey.M && screen[top - 1, left].type == 'X') {
						screen[top - 1, left].type = '>';
						++this.flagCount;
					} else if (consoleKey.Key == ConsoleKey.M && screen[top - 1, left].type == '>') {
						screen[top - 1, left].type = '?';
						--this.flagCount;
					} else if (consoleKey.Key == ConsoleKey.M && screen[top - 1, left].type == '?') {
						screen[top - 1, left].type = 'X';
					}
						// F1
					else if (consoleKey.Key == ConsoleKey.F1) {
						this.PrintTable();
						Console.ReadKey();
					}
					if (exit == false) {
						exit = this.IsEnd();
					}
					this.PrintScreen(left, top);
				}
			}
			this.End();
		}

		private bool IsEnd() {
			for (int i = 0; i < this.height; ++i) {
				for (int j = 0; j < this.width; ++j) {
					if ((this.screen[i, j].type == '>' && this.table[i, j].type == '*')
								|| (this.screen[i, j].type == ' ' && this.table[i, j].type == '0')
								|| (this.screen[i, j].type >= '1' && this.screen[i, j].type <= '8'
								&& this.screen[i, j].type == this.table[i, j].type)) {
						;
					} else {
						return false;
					}
				}
			}
			return true;
		}

		private bool GetPositiveNumberOfMine(char c, out int result) {
			result = -1;
			if (c > '0' && c < '9') {
				result = Int32.Parse(c.ToString());
				return true;
			}
			return false;
		}

		private int GetNumberOfNeighbouringFlags(int i, int j) {
			int counter = 0;
			// north
			if (i > 0 && this.screen[i - 1, j].type == '>') {
				++counter;
			}
			// north-east
			if (i > 0 && j < this.width - 1 && this.screen[i - 1, j + 1].type == '>') {
				++counter;
			}
			// east
			if (j < this.width - 1 && this.screen[i, j + 1].type == '>') {
				++counter;
			}
			// south-east
			if (i < this.height - 1 && j < this.width - 1 && this.screen[i + 1, j + 1].type == '>') {
				++counter;
			}
			// south
			if (i < this.height - 1 && this.screen[i + 1, j].type == '>') {
				++counter;
			}
			// south-west
			if (i < this.height - 1 && j > 0 && this.screen[i + 1, j - 1].type == '>') {
				++counter;
			}
			// west
			if (j > 0 && this.screen[i, j - 1].type == '>') {
				++counter;
			}
			// north-west
			if (i > 0 && j > 0 && this.screen[i - 1, j - 1].type == '>') {
				++counter;
			}
			return counter;
		}

		private void ShowSquare(int top, int left, out bool exit) {
			exit = false;
			if (this.screen[top, left].type == 'X') {
				if (this.table[top, left].type == '0') {
					this.screen[top, left].type = ' ';
					this.ShowNeighbours(top, left);
				} else if (this.table[top, left].type == '*') {
					this.screen[top, left].type = this.table[top, left].type;
					exit = true;
				} else {
					this.screen[top, left].type = this.table[top, left].type;
				}
			}
		}

		private void ShowHidedNeighbours(int i, int j, int result, out bool exit) {
			bool exit2;
			exit = false;
			int n = this.GetNumberOfNeighbouringFlags(i, j);
			if (n == result) {
				// north
				if (i > 0) {
					this.ShowSquare(i - 1, j, out exit2);
					if (exit2) {
						exit = true;
					}
				}
				// north-east
				if (i > 0 && j < this.width - 1) {
					this.ShowSquare(i - 1, j + 1, out exit2);
					if (exit2) {
						exit = true;
					}
				}
				// east
				if (j < this.width - 1) {
					this.ShowSquare(i, j + 1, out exit2);
					if (exit2) {
						exit = true;
					}
				}
				// south-east
				if (i < this.height - 1 && j < this.width - 1) {
					this.ShowSquare(i + 1, j + 1, out exit2);
					if (exit2) {
						exit = true;
					}
				}
				// south
				if (i < this.height - 1) {
					this.ShowSquare(i + 1, j, out exit2);
					if (exit2) {
						exit = true;
					}
				}
				// south-west
				if (i < this.height - 1 && j > 0) {
					this.ShowSquare(i + 1, j - 1, out exit2);
					if (exit2) {
						exit = true;
					}
				}
				// west
				if (j > 0) {
					this.ShowSquare(i, j - 1, out exit2);
					if (exit2) {
						exit = true;
					}
				}
				// north-west
				if (i > 0 && j > 0) {
					this.ShowSquare(i - 1, j - 1, out exit2);
					if (exit2) {
						exit = true;
					}
				}

				this.PrintScreen(j, i + 1);
			} else {
				this.PrintScreen(j, i + 1);
				// north
				if (i > 0) {
					this.EmphasiseSquare(i - 1, j);
				}
				// north-east
				if (i > 0 && j < this.width - 1) {
					this.EmphasiseSquare(i - 1, j + 1);
				}
				// east
				if (j < this.width - 1) {
					this.EmphasiseSquare(i, j + 1);
				}
				// south-east
				if (i < this.height - 1 && j < this.width - 1) {
					this.EmphasiseSquare(i + 1, j + 1);
				}
				// south
				if (i < this.height - 1) {
					this.EmphasiseSquare(i + 1, j);
				}
				// south-west
				if (i < this.height - 1 && j > 0) {
					this.EmphasiseSquare(i + 1, j - 1);
				}
				// west
				if (j > 0) {
					this.EmphasiseSquare(i, j - 1);
				}
				// north-west
				if (i > 0 && j > 0) {
					this.EmphasiseSquare(i - 1, j - 1);
				}

				Console.SetCursorPosition(i, j + 1);
				Console.CursorVisible = true;
				Console.BackgroundColor = ConsoleColor.White;
				Console.ForegroundColor = ConsoleColor.Black;
			}
		}

		private void EmphasiseSquare(int top, int left) {
			if (this.screen[top, left].type == 'X') {
				Console.ForegroundColor = ConsoleColor.Green;

				Console.SetCursorPosition(left, top + 1);
				Console.CursorVisible = true;
				Console.Write('X');
			}

		}

		private void ShowNeighbours(int top, int left) {
			if (this.table[top, left].type == '0') {
				this.screen[top, left].type = ' ';
				// north
				if (top > 0 && this.screen[top - 1, left].type == 'X') {
					this.ShowNeighbours(top - 1, left);
				}
					// north-east
				if (top > 0 && left < this.width - 1 && this.screen[top - 1, left + 1].type == 'X') {
					this.ShowNeighbours(top - 1, left + 1);
				}
					// east
				if (left < this.width - 1 && this.screen[top, left + 1].type == 'X') {
					this.ShowNeighbours(top, left + 1);
				}
					// south-east
				if (top < this.height - 1 && left < this.width - 1 && this.screen[top + 1, left + 1].type == 'X') {
					this.ShowNeighbours(top + 1, left + 1);
				}
					// south
				if (top < this.height - 1 && this.screen[top + 1, left].type == 'X') {
					this.ShowNeighbours(top + 1, left);
				}
					// south-west
				if (top < this.height - 1 && left > 0 && this.screen[top + 1, left - 1].type == 'X') {
					this.ShowNeighbours(top + 1, left - 1);
				}
					// west
				if (left > 0 && this.screen[top, left - 1].type == 'X') {
					this.ShowNeighbours(top, left - 1);
				}
					// north-west
				if (top > 0 && left > 0 && this.screen[top - 1, left - 1].type == 'X') {
					this.ShowNeighbours(top - 1, left - 1);
				}
			} else if (this.table[top, left].type >= '1' && this.table[top, left].type <= '8') {
				this.screen[top, left].type = this.table[top, left].type;
			}
		}

		private void End() {
			System.Timers.Timer aTimer = new System.Timers.Timer();
			aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
			aTimer.Interval = 1000;
			aTimer.Enabled = true;

			Console.ReadLine();
			GC.KeepAlive(aTimer);
		}

		private void OnTimedEvent(object source, ElapsedEventArgs e) {
			if (this.printTable == true) {
				this.printTable = false;
				this.PrintTable();
			} else {
				this.printTable = true;
				this.PrintScreen();
			}
		}


		private void PrintTable() {
			Console.Clear();

			Console.WriteLine(this.mineCount - this.flagCount);
			for (int i = 0; i < this.height; ++i) {
				for (int j = 0; j < this.width; ++j) {
					Console.Write(this.table[i, j].type);
				}
				if (i < this.height - 1) {
					Console.WriteLine("");
				}
			}
		}

		private void PrintScreen() {
			Console.BackgroundColor = ConsoleColor.Black;
			Console.ForegroundColor = ConsoleColor.White;

			Console.Clear();

			Console.WriteLine(this.mineCount - this.flagCount);
			for (int i = 0; i < this.height; ++i) {
				for (int j = 0; j < this.width; ++j) {
					Console.Write(this.screen[i, j].type);
				}
				if (i < this.height - 1) {
					Console.WriteLine("");
				}
			}
		}

		private void PrintScreen(int left, int top) {
			Console.BackgroundColor = ConsoleColor.Black;
			Console.ForegroundColor = ConsoleColor.White;

			Console.Clear();

			Console.WriteLine(this.mineCount - this.flagCount);
			for (int i = 0; i < this.height; ++i) {
				for (int j = 0; j < this.width; ++j) {
					Console.Write(this.screen[i, j].type);
				}
				if (i < this.height - 1) {
					Console.WriteLine("");
				}
			}

			Console.SetCursorPosition(left, top);
			Console.CursorVisible = true;
			Console.BackgroundColor = ConsoleColor.White;
			Console.ForegroundColor = ConsoleColor.Black;
			Console.Write(this.screen[top - 1, left].type);
			Console.SetCursorPosition(left, top);
		}

		public bool printTable = true;
		public Square[,] screen;
		public Square[,] table;
		public int height;
		public int width;
		public int mineCount;
		public int flagCount;
	}

	class Program {
		static void Main(string[] args) {
			// Check a number of parameters.
			try {
				if (args.Length != 3) {
					throw new Exception("My: bad number of parameters");
				}
				int result;
				if (Int32.TryParse(args[0], out result) == false
						|| Int32.TryParse(args[1], out result) == false
						|| Int32.TryParse(args[2], out result) == false) {
					throw new Exception("My: bad type of parameters");
				}
				if (Int32.Parse(args[0]) < 1 || Int32.Parse(args[1]) < 1) {
					throw new Exception("My: dimensions of a table must be greater than zero");
				}
			} catch (Exception e) {
				Console.Error.WriteLine(e.Message);
			}

			try {
				mineTable.GenerateTable(Int32.Parse(args[0]), Int32.Parse(args[1]), Int32.Parse(args[2]));
				mineTable.Run();
			} catch (Exception e) {
				Console.Error.WriteLine(e.Message);
			}
		}

		private static MineTable mineTable = new MineTable();
	}
}