using MySqlConnector;
using DBObj;
using System.Globalization; 
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["歌曲編號"].ToString();
                            string category = reader["語別"].ToString();
                            string song = reader["歌曲名稱"].ToString();
                            int plays = Convert.ToInt32(reader["點播次數"]);
                            string artistA = reader["歌星 A"].ToString();
                            string artistB = reader["歌星 B"].ToString();
                            string artistACategory = reader["歌星A分類"].ToString();
                            string artistBCategory = reader["歌星B分類"].ToString();
                            string dateValue = reader["新增日期"]?.ToString() ?? "";
                            DateTime addedTime;
                            try
                            {
                                addedTime = DateTime.Parse(dateValue, CultureInfo.InvariantCulture).Date;
                            }
                            catch
                            {
                                addedTime = DateTime.Today;
                            }

                            string basePathHost1 = reader["路徑 1"].ToString();
                            string basePathHost2 = reader["路徑 2"].ToString();
                            string fileName = reader["歌曲檔名"].ToString();
                            string songFilePathHost1 = Path.Combine(basePathHost1, fileName);
                            string songFilePathHost2 = Path.Combine(basePathHost2, fileName);
                            string phoneticNotation = reader["歌曲注音"].ToString();
                            string pinyinNotation = reader["歌曲拼音"].ToString();
                            string artistAPhonetic = reader["歌星A注音"].ToString();
                            string artistBPhonetic = reader["歌星B注音"].ToString();
                            string artistASimplified = reader["歌星A簡體"].ToString();
                            string artistBSimplified = reader["歌星B簡體"].ToString();
                            string songSimplified = reader["歌名簡體"].ToString();
                            string songGenre = reader["分類"].ToString();
                            string artistAPinyin = reader["歌星A拼音"].ToString();
                            string artistBPinyin = reader["歌星B拼音"].ToString();
                            int humanVoice = Convert.ToInt32(reader["人聲"]);

                            searchResults.Add(new SongData(
                                songNumber, category, song, plays, artistA, artistB,
                                artistACategory, artistBCategory, addedTime,
                                songFilePathHost1, songFilePathHost2,
                                phoneticNotation, pinyinNotation,
                                artistAPhonetic, artistBPhonetic,
                                artistASimplified, artistBSimplified,
                                songSimplified, songGenre,
                                artistAPinyin, artistBPinyin,
                                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();
                            searchResults.Add(new Artist(artist));
                        }
                    }
                }
                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.歌曲編號, sl.語別, sl.歌曲名稱, sl.點播次數, " +
                "sl.`歌星 A`, sl.`歌星 B`, sl.新增日期, " +
                "sl.`路徑 1`, sl.`路徑 2`, sl.歌曲檔名, sl.歌曲注音, sl.歌曲拼音, " +
                "sl.歌星A分類, sl.歌星B分類, sl.歌星A注音, sl.歌星B注音, " +
                "sl.歌星A簡體, sl.歌星B簡體, sl.歌名簡體, sl.分類, " +
                "sl.歌星A拼音, sl.歌星B拼音, sl.人聲 " +
                "FROM FavoriteSongs fs " +
                "JOIN SongLibrary sl ON fs.SongNumber = sl.歌曲編號 " +
                $"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);
        }


    }

}