using MySqlConnector;
using DBObj;
using System.IO;
using System.Diagnostics;

namespace DualScreenDemo{
    public partial class PrimaryForm
    {
        
        private static string GetConnectionString()
        {
            return Utils.Env.GetDBConnection();
        }

        public bool isLoggedIn = false;
        public string userPhone = string.Empty;
        public  List<SongData> SearchSongs_Mysql(string query)
        {
            List<SongData> searchResults = new List<SongData>();
            Console.WriteLine(query);
            //string connectionString = "Server=192.168.11.4;Port=3306;Database=Karaoke-Kingpin;User=Karaoke-Kingpin;Password=ESM7yTPMnavFmbBH;";
            string connectionString = GetConnectionString();
            using (var connection = new MySqlConnection(connectionString))
            {
                Stopwatch stopwatch = new Stopwatch();

                connection.Open();
                
                stopwatch.Start();

                Console.WriteLine("MyDB 連線成功！");

                using (var command = new MySqlCommand(query, connection))
                {

                    using (var reader = command.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            searchResults.Add(new SongData(
                                reader["song_id"].ToString(),
                                reader["song_name"].ToString(),
                                reader["artistA"].ToString(),
                                reader["artistB"].ToString(),
                                reader["song_filename"].ToString(), 
                                reader["artistA_simplified"].ToString(),
                                reader["artistB_simplified"].ToString(),
                                reader["song_simplified"].ToString(),
                                Convert.ToInt32(reader["vocal"])
                            ));
                        }
                    }
                }

                connection.Close();
                stopwatch.Stop();
                Console.WriteLine($"MyDB 連線已關閉！執行時間: {stopwatch.ElapsedMilliseconds} 毫秒");
                writeLogforSearchTime(stopwatch.ElapsedMilliseconds);
                Console.WriteLine($"查詢到 {searchResults.Count} 筆資料。");
            }

            return searchResults;
        }
        public static List<Artist> SearchSingers_Mysql(string query){
            List<Artist> searchResults = new List<Artist>();
            Console.WriteLine(query);
            //string connectionString = "Server=192.168.11.4;Port=3306;Database=Karaoke-Kingpin;User=Karaoke-Kingpin;Password=ESM7yTPMnavFmbBH;";
            string connectionString = GetConnectionString();
            using (var connection = new MySqlConnection(connectionString))
            {
                Stopwatch stopwatch = new Stopwatch();
                connection.Open();
                stopwatch.Start();
                Console.WriteLine("MyDB 連線成功！");

                using (var command = new MySqlCommand(query, connection))
                {

                    using (var reader = command.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            string artist = reader["name"].ToString();
                            string artistSimplified = reader ["simplified"].ToString();
                            searchResults.Add(new Artist(artist,artistSimplified));
                        }
                    }
                }
                connection.Close();
                stopwatch.Stop();
                Console.WriteLine($"MyDB 連線已關閉！執行時間: {stopwatch.ElapsedMilliseconds} 毫秒");
                writeLogforSearchTime(stopwatch.ElapsedMilliseconds);
                Console.WriteLine($"查詢到 {searchResults.Count} 筆資料。");
            }
            return searchResults;

        }
        public void InsertNewFavoriteSong(string songNumber){
            
            string query = $"INSERT INTO FavoriteSongs (userPhone,songNumber) VALUES ('{userPhone}','{songNumber}');";
            Console.WriteLine(query);
            //string connectionString = "Server=192.168.11.4;Port=3306;Database=Karaoke-Kingpin;User=Karaoke-Kingpin;Password=ESM7yTPMnavFmbBH;";
            string connectionString = GetConnectionString();
            using (var connection = new MySqlConnection(connectionString))
            {
                
                connection.Open();
                Console.WriteLine("MyDB 連線成功！");

                using (var command = new MySqlCommand(query, connection))
                {
                    int rowsAffected = command.ExecuteNonQuery();
                    if (rowsAffected > 0)
                    {
                        Console.WriteLine("插入成功！");
                    }
                    else
                    {
                        Console.WriteLine("插入失敗（沒有資料被新增）");
                    }
                }
                connection.Close();
                Console.WriteLine("MyDB 連線已關閉！");
            }
        }
        public void InsertNewFavoriteUser(string phonenumber){
            string songlist = phonenumber + "的歌單";
            string query = $"INSERT INTO FavoriteSongs (userPhone,songNumber) VALUES ('{phonenumber}','{songlist}');";
            Console.WriteLine(query);
            //string connectionString = "Server=192.168.11.4;Port=3306;Database=Karaoke-Kingpin;User=Karaoke-Kingpin;Password=ESM7yTPMnavFmbBH;";
            string connectionString = GetConnectionString();
            using (var connection = new MySqlConnection(connectionString))
            {
                
                connection.Open();
                Console.WriteLine("MyDB 連線成功！");

                using (var command = new MySqlCommand(query, connection))
                {
                    int rowsAffected = command.ExecuteNonQuery();
                    if (rowsAffected > 0)
                    {
                        Console.WriteLine("插入成功！");
                    }
                    else
                    {
                        Console.WriteLine("插入失敗（沒有資料被新增）");
                    }
                }
                connection.Close();
                Console.WriteLine("MyDB 連線已關閉！");
            }
        }
        public string SearchFavoriteSongs_Mysql()
        {
            string query = $"SELECT " +
                "sl.*" +
                "FROM FavoriteSongs fs " +
                "JOIN song_library_cache sl ON fs.songNumber = sl.song_id " +
                $"WHERE fs.userPhone = '{userPhone}';";
            return query;

        }
        public bool checkPhoneNumberExist(string phonenumber){
            //string connectionString = "Server=192.168.11.4;Port=3306;Database=Karaoke-Kingpin;User=Karaoke-Kingpin;Password=ESM7yTPMnavFmbBH;";
            string connectionString = GetConnectionString();
            bool exists = false;
            using (var connection = new MySqlConnection(connectionString))
            {
                connection.Open();
                Console.WriteLine("MyDB 連線成功！");
                string query = $"SELECT COUNT(*) FROM FavoriteSongs WHERE userPhone = '{phonenumber}';";
                using (var command = new MySqlCommand(query, connection))
                {
                    int count = Convert.ToInt32(command.ExecuteScalar());
                    if (count > 0)
                    {
                        exists = true; // 存在
                        userPhone = phonenumber;
                        isLoggedIn = true;
                        //點歌我的最愛按鈕，調整按鈕狀態
                        favoriteButton.Enabled = true;
                        favoriteButton.BackColor = Color.Transparent;
                        disabledPanel.Visible = false;
                        this.Invalidate();
                    }
                    else
                    {
                        exists = false; // 不存在
                    }
                }
                connection.Close();
                Console.WriteLine("MyDB 連線關閉！");
                
            }
            return exists;
        }
        public void logout(){
            isLoggedIn=false;
            userPhone=string.Empty;
        }
        //private static int countforSearch = 0;
        private static void writeLogforSearchTime(long elapsedMs){
            /*
            countforSearch++;

            string logFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "txt", "searchTimeLog.txt");
            string data = $"{countforSearch}, {elapsedMs} " + Environment.NewLine;
            File.AppendAllText(logFilePath, data);
            */
        }

        public void AddSongCount(string id){
            string query = $"UPDATE song_library_cache SET song_counts = song_counts+1 WHERE song_id = '{id}';";
            Console.WriteLine(query);
            //string connectionString = "Server=192.168.11.4;Port=3306;Database=Karaoke-Kingpin;User=Karaoke-Kingpin;Password=ESM7yTPMnavFmbBH;";
            string connectionString = GetConnectionString();
            using (var connection = new MySqlConnection(connectionString))
            {
                
                connection.Open();
                Console.WriteLine("MyDB 連線成功！");

                using (var command = new MySqlCommand(query, connection))
                {
                    int rowsAffected = command.ExecuteNonQuery();
                    if (rowsAffected > 0)
                    {
                        Console.WriteLine("新增成功！");
                    }
                    else
                    {
                        Console.WriteLine("新增失敗（點播次數沒有新增）");
                    }
                }
                connection.Close();
                Console.WriteLine("MyDB 連線已關閉！");
            }
        }

    }

}