using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;


namespace SpaceInvaders
{
    public class Menu
    {
        //Options de menu
        string[] menuOptions = { "  1. Jouer        ",
                                 "  2. Options      ",
                                 "  3. Highscore    ",
                                 "  4. Résultats    ",
                                 "  5. Quitter      " };
        //Option selectionnée
        int selectedOption = 0;

        /// <summary>
        /// Fonction pour démarrer le menu principal
        /// </summary>
        public void StartMenu()
        {
            while (true)
            {
                
                Console.BackgroundColor = ConsoleColor.DarkMagenta;
                Console.Clear();
                Console.BackgroundColor = ConsoleColor.White;
                Console.ForegroundColor = ConsoleColor.DarkMagenta;

                Console.SetCursorPosition(50, 4);
                Console.WriteLine("┌──────────────────┐");
                Console.SetCursorPosition(50, 5);
                Console.WriteLine("│ Spicy Invader II │");
                Console.SetCursorPosition(50, 6);
                Console.WriteLine("└──────────────────┘");

                
                for (int i = 0; i < menuOptions.Length; i++)
                {
                    Console.CursorVisible = false;
                    Console.SetCursorPosition(51, 7 + i);
                    if (i == selectedOption)
                    {
                        Console.ForegroundColor = ConsoleColor.White;
                        Console.BackgroundColor = ConsoleColor.DarkMagenta;
                    }
                    else
                    {
                        Console.ForegroundColor = ConsoleColor.Gray;
                        Console.BackgroundColor = ConsoleColor.Black;
                    }

                    Console.WriteLine(menuOptions[i]);
                }

                Console.ResetColor();

                // Gère la saisie clavier pour le menu

                ConsoleKeyInfo keyInfo = Console.ReadKey();
                if (keyInfo.Key == ConsoleKey.UpArrow)
                {
                    selectedOption = (selectedOption - 1 + menuOptions.Length) % menuOptions.Length;
                }
                else if (keyInfo.Key == ConsoleKey.DownArrow)
                {
                    selectedOption = (selectedOption + 1) % menuOptions.Length;
                }
                else if (keyInfo.Key == ConsoleKey.Enter)
                {
                    if (selectedOption == menuOptions.Length - 1)
                    {
                        break; // Sortir du boucle
                    }
                    else
                    {
                        PerformAction(selectedOption);

                        Console.ReadKey();
                    }
                }
            }
        }
        /// <summary>
        ///  Gère les actions de chaque option de menu
        /// </summary>
        /// <param name="option">option selectionnée</param>
        static void PerformAction(int option)
        {
            DatabaseConnection databaseConnection = new DatabaseConnection();
            switch (option)
            {
                case 0: //Jouer
                    StartGame();
                    break;

                case 1: //Options
                    Console.Clear();
                    Console.WriteLine("");
                    break;

                case 2: //Highscore
                    Console.Clear();
                    var scores = databaseConnection.GetTop5Highscores();

                    Console.WriteLine("------- Highscores -------");
                    foreach (var (playerName, score) in scores)
                    {
                        Console.WriteLine($"{playerName}: {score}");
                    }

                    Console.WriteLine("\nAppuyez sur une touche pour retourner au menu");
                    break;

                case 3: //Résultats
                    Console.Clear();
                    Console.WriteLine("");
                    break;

                case 4: //Quitter
                    Console.ReadKey();

                    break;

            }
        }
        /// <summary>
        /// Méthode pour lancer le jeu
        /// </summary>
        public static void StartGame()
        {
            Console.BackgroundColor = ConsoleColor.DarkMagenta;
            
            Console.Write("\nEcrivez votre nickname: ");
            string playerName1 = Console.ReadLine();

            Console.Clear();

            Console.BackgroundColor = ConsoleColor.White;
            Enemy monEnnemi = new Enemy(18, 0);
            Ship monVaisseau = new Ship(18, 10);
            List<Enemy> listEnemies = new List<Enemy>();
            for (int x = 18; x <= 38; x += 2)
            {
                listEnemies.Add(new Enemy(x, 0));
            }
            for (int x = 18; x <= 38; x += 2)
            {
                listEnemies.Add(new Enemy(x, 1));
            }
            for (int x = 18; x <= 38; x += 2)
            {
                listEnemies.Add(new Enemy(x, 2));
            }
            game game = new game(listEnemies, monVaisseau);
            game.StartGame();
            int finalScore = game.score;
            DatabaseConnection databaseConnection = new DatabaseConnection();
            databaseConnection.SaveScore(playerName1, finalScore);
        }

        /// <summary>
        /// Classe pour la connexion à la base de données
        /// </summary>
        public class DatabaseConnection
        {
            private string connectionString = "Server=localhost;Port=6033;Database=db_space_invaders;User Id=root;Password=root;";
            public void TestConnection()
            {
                using (MySqlConnection connection = new MySqlConnection(connectionString))
                {
                    try
                    {
                        connection.Open();
                        Console.WriteLine("Connexion OK");
                    }
                    catch (MySqlException ex)
                    {
                        Console.WriteLine($"Erreur {ex.Message}");
                    }
                }
            }
            /// <summary>
            /// Récupère les 5 meilleures scores
            /// </summary>
            /// <returns></returns>
            public List<(string playerName, int score)> GetTop5Highscores()
            {
                List<(string playerName, int score)> highscores = new List<(string playerName, int score)>();

                using (MySqlConnection connection = new MySqlConnection(connectionString))
                {
                    try
                    {
                        connection.Open();

                        string query = "SELECT jouPseudo, jouNombrePoints FROM t_joueur ORDER BY jouNombrePoints DESC LIMIT 5";

                        MySqlCommand cmd = new MySqlCommand(query, connection);
                        using (MySqlDataReader reader = cmd.ExecuteReader())
                        {
                            while (reader.Read())
                            {
                                highscores.Add((reader.GetString(0), reader.GetInt32(1)));
                            }
                        }
                    }
                    catch (MySqlException ex)
                    {
                        Console.WriteLine($"Erreur {ex.Message}");

                    }
                }
                return highscores;
            }
            /// <summary>
            ///  // Sauvegarde le score dans la base de données
            /// </summary>
            /// <param name="playerName">Nom du joueur</param>
            /// <param name="score">Score final stocké</param>
            public void SaveScore(string playerName, int score)
            {
                using (MySqlConnection connection = new MySqlConnection(connectionString))
                {
                    try
                    {
                        connection.Open();

                        string query = "INSERT INTO t_joueur (jouPseudo, jouNombrePoints) VALUES (@playerName, @score)";
                        MySqlCommand cmd = new MySqlCommand(query, connection);
                        cmd.Parameters.AddWithValue("@playerName", playerName);
                        cmd.Parameters.AddWithValue("@score", score);

                        cmd.ExecuteNonQuery();
                    }
                    catch (MySqlException ex)
                    {
                        Console.WriteLine($"Erreur {ex.Message}");
                    }
                }
            }
        }
    }
}
