﻿namespace ConsoleApp {
  internal class Program {
    static void Main(string[] args) {

      // Available types of cards expressed in letters
      const string TYPESOFCARDS = ("ABCDEFGHIJK");

      // Playing field size
      const int ROWS    = 4;
      const int COLUMNS = 6;

      // Number of cards in play
      const int NUMBEROFCARDS = ROWS * COLUMNS;

      Console.WriteLine("Field size: " + ROWS + "x" + COLUMNS + " | Number of cards: " + NUMBEROFCARDS);
      Console.WriteLine("Available card types: " + TYPESOFCARDS);

      // Initialize character array to hold cards
      char[] cards = new char[0];

      // Add paired and sorted sets of cards as required
      while (cards.Length < NUMBEROFCARDS) {
        char[] pairedSet = (TYPESOFCARDS + TYPESOFCARDS).ToCharArray();
        Array.Sort(pairedSet);
        cards = cards.Concat(pairedSet).ToArray();
      }

      Console.WriteLine();
      Console.WriteLine("Initial sets of pairs:    " + new string(cards));
      

      // Limit cards to necessary number
      Array.Resize(ref cards, NUMBEROFCARDS);

      Console.WriteLine("Actually required cards:  " + new string(cards));

      // Shuffle cards
      Random.Shared.Shuffle(cards);

      Console.WriteLine("Cards have been shuffled: " + new string(cards));

      Console.WriteLine();

      DrawField(COLUMNS, cards);

      Console.WriteLine();

      bool running = true;

      int x = Console.GetCursorPosition().Item1;
      int y = Console.GetCursorPosition().Item2;

      do {      
        //DrawField();
        Console.SetCursorPosition(x, y);

        string userInput = Console.ReadKey(true).Key.ToString();

        switch (userInput) {
          // Move cursor with arrow keys
          case "UpArrow":
            Console.SetCursorPosition(x, y - 1);
            break;
          case "DownArrow":
            Console.SetCursorPosition(x, y + 1);
            break;
          case "LeftArrow":
            Console.SetCursorPosition(x - 1, y);
            break;
          case "RightArrow":
            Console.SetCursorPosition(x + 1, y);
            break;
          // Do something on Enter
          case "Enter":
            Console.Write(" ");
            break;
          // End program on Escape
          case "Escape":
            Console.WriteLine("User pressed Escape, exiting...");
            running = false;
            break;

        }

        x = Console.GetCursorPosition().Item1;
        y = Console.GetCursorPosition().Item2;

      } while (running);
    }

    // Draw the playing field
    static void DrawField(int COLUMNS, char[] cards) {

      //Console.Clear();
      
      for (int i = 0; i < cards.Length; i++) {
        Console.Write(cards[i] + " ");
        if ((i+1) % COLUMNS == 0) {
          Console.Write("\n");
        }
      }
    }
  }
}
