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

namespace DualScreenDemo{
    public partial class PrimaryForm
    {
        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;";
            
            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 songNumber = reader["song_id"].ToString();
                            string song = reader["song_name"].ToString();
                            string artistA = reader["artistA"].ToString();
                            string artistB = reader["artistB"].ToString();
                            string fileName = reader["song_filename"].ToString();
                            string songFilePathHost1 = Path.Combine(@"\\SVR01\DISK05", fileName); // \SVR01\DISK01\
                            string songFilePathHost2 = Path.Combine(@"\\SVR02\DISK01", fileName); // \SVR02\DISK01\
                            string artistASimplified = reader["artistA_simplified"].ToString(); 
                            string artistBSimplified = reader["artistB_simplified"].ToString();
                            string songSimplified = reader["song_simplified"].ToString();
                            int humanVoice = Convert.ToInt32(reader["vocal"]);

                            searchResults.Add(new SongData(
                                songNumber,  song,  artistA, artistB, 
                                songFilePathHost1, songFilePathHost2,
                                artistASimplified, artistBSimplified,
                                songSimplified, humanVoice
                            ));
                        }
                    }
                }

                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;";

            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 (Phonenumber,SongNumber) VALUES ('{userPhone}','{songNumber}');";
            Console.WriteLine(query);
            string connectionString = "Server=192.168.11.4;Port=3306;Database=Karaoke-Kingpin;User=Karaoke-Kingpin;Password=ESM7yTPMnavFmbBH;";

            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.Phonenumber = '{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;";
            bool exists = false;
            using (var connection = new MySqlConnection(connectionString))
            {
                connection.Open();
                Console.WriteLine("MyDB 連線成功！");
                string query = $"SELECT COUNT(*) FROM FavoriteSongs WHERE Phonenumber = '{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;
                        }
                        else
                        {
                            exists = false; // 不存在
                        }
                }
                connection.Close();
                Console.WriteLine("MyDB 連線關閉！");
            }
            return exists;
        }
        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);
        }


    }

}