using System.Data.SQLite;
using System.IO;
using System.Globalization;  
using System.Diagnostics;
using DualScreenDemo;
namespace DBObj
{
    public class SongListManager
    {
        private static SongListManager _instance;
        public List<SongData> AllSongs { get; private set; }
        public static Dictionary<string, List<SongData>> NewSongLists { get; private set; }
        public static Dictionary<string, List<SongData>> HotSongLists { get; private set; }
        public List<SongData> FavoriteSongs { get; private set; }  
        //public const int SongsPerPage = 9;

        public bool IsUserLoggedIn { get; set; }  
        public string UserPhoneNumber { get; set; }  

        public SongListManager()
        {
            AllSongs = new List<SongData>();
            NewSongLists = new Dictionary<string, List<SongData>>();
            HotSongLists = new Dictionary<string, List<SongData>>();
            FavoriteSongs = new List<SongData>();

            // 尝试更新数据库，但无论结果如何都继续运行
            //TryUpdateDatabase();

            // 继续使用可用的数据库（可能是更新后的或原本的本地数据库）
            //InitializeDatabase();
            //LoadSongs();
            //InitializeNewSongLists();
            //InitializeHotSongLists();
        }
        
        /*
        private bool TryUpdateDatabase()
        {
            try 
            {
                // 1. 检查是否能连接到 SVR01
                if (!Directory.Exists(@"\\SVR01\SuperstarB"))
                {
                    Console.WriteLine("未連接到SVR使用本地DB");
                    return true; // 继续使用本地数据库
                }

                // 2. 比较本地和服务器文件
                string localDbPath = Path.Combine(Application.StartupPath,"db" ,"KSongDatabase.db");
                string serverDbPath = @"\\SVR01\SuperstarB\KSongDatabase.db";

                if (!File.Exists(localDbPath))
                {
                    Console.WriteLine("本地無db");
                }
                else
                {
                    FileInfo localFile = new FileInfo(localDbPath);
                    FileInfo serverFile = new FileInfo(serverDbPath);

                    if (serverFile.LastWriteTime <= localFile.LastWriteTime)
                    {
                        Console.WriteLine("歌單已是最新");
                        return true;
                    }
                }

                // 3. 需要更新时，复制新文件
                Process copyProcess = new Process();
                copyProcess.StartInfo.FileName = "cmd.exe";
                copyProcess.StartInfo.Arguments = "/C copy /Y \\\\SVR01\\SuperstarB\\KSongDatabase.db \\db\\KSongDatabase.db";
                copyProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                copyProcess.StartInfo.CreateNoWindow = true;
                copyProcess.Start();
                copyProcess.WaitForExit();

                if (copyProcess.ExitCode == 0)
                {
                    Console.WriteLine("歌單更新成功");
                }
                else
                {
                    Console.WriteLine("歌單複製失敗，使用本地歌單");
                }

                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"更新歌單失敗：{ex.Message}");
                return true; // 出错时继续使用本地数据库
            }
        }
        */
        public static SongListManager Instance
        {
            get
            {
                if (_instance == null)
                {
                    _instance = new SongListManager();
                }
                return _instance;
            }
        }

        public List<SongData> GetSongsByArtist(string artistName)
        {
            return AllSongs.Where(song => song.ArtistA == artistName || song.ArtistB == artistName).ToList();
        }

        public void InitializeDatabase()
        {
            string databaseFileName = "KSongDatabase.db";
            string databasePath = Path.Combine(Application.StartupPath, "db", databaseFileName);
            string connectionString = String.Format("Data Source={0};Version=3;", databasePath);

            using (var connection = new SQLiteConnection(connectionString))
            {
                try
                {
                    connection.Open();
                    string createTableSql = @"
                        CREATE TABLE IF NOT EXISTS FavoriteSongs (
                            PhoneNumber TEXT NOT NULL,
                            SongNumber TEXT NOT NULL,
                            PRIMARY KEY (PhoneNumber, SongNumber)
                        );";
                    using (var command = new SQLiteCommand(createTableSql, connection))
                    {
                        command.ExecuteNonQuery();
                    }

                    connection.Close();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Failed to initialize SQLite database: " + ex.Message);
                }
            }
        }

        public void AddNewUser(string phoneNumber)
        {
            string databaseFileName = "KSongDatabase.db";
            string databasePath = Path.Combine(Application.StartupPath, "db", databaseFileName);
            string connectionString = String.Format("Data Source={0};Version=3;", databasePath);

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

                    
                    string checkTableSql = "SELECT name FROM sqlite_master WHERE type='table' AND name='FavoriteSongs';";
                    using (var checkCommand = new SQLiteCommand(checkTableSql, connection))
                    {
                        var result = checkCommand.ExecuteScalar();
                        if (result == null)
                        {
                            throw new Exception("Table 'FavoriteSongs' does not exist.");
                        }
                    }

                    string sql = "INSERT INTO FavoriteSongs (PhoneNumber, SongNumber) VALUES (@PhoneNumber, @SongNumber)";
                    using (var command = new SQLiteCommand(sql, connection))
                    {
                        command.Parameters.AddWithValue("@PhoneNumber", phoneNumber);
                        command.Parameters.AddWithValue("@SongNumber", "000000");
                        command.ExecuteNonQuery();
                    }
                    connection.Close();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Failed to add new user to SQLite database: " + ex.Message);
                }
            }
        }
        
        public void AddToFavorite(string songNumber)
        {
            if (!IsUserLoggedIn || string.IsNullOrEmpty(UserPhoneNumber))
            {
                Console.WriteLine("User is not logged in.");
                return;
            }

            string databaseFileName = "KSongDatabase.db";
            string databasePath = Path.Combine(Application.StartupPath, "db", databaseFileName);
            string connectionString = String.Format("Data Source={0};Version=3;", databasePath);

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

                    
                    string checkSql = "SELECT COUNT(*) FROM FavoriteSongs WHERE PhoneNumber = @PhoneNumber AND SongNumber = @SongNumber";
                    using (var checkCommand = new SQLiteCommand(checkSql, connection))
                    {
                        checkCommand.Parameters.AddWithValue("@PhoneNumber", UserPhoneNumber);
                        checkCommand.Parameters.AddWithValue("@SongNumber", songNumber);
                        long count = (long)checkCommand.ExecuteScalar();

                        if (count > 0)
                        {
                            
                            Console.WriteLine(String.Format("Song {0} is already in favorites.", songNumber));
                            return;
                        }
                    }

                    string sql = "INSERT INTO FavoriteSongs (PhoneNumber, SongNumber) VALUES (@PhoneNumber, @SongNumber)";
                    using (var command = new SQLiteCommand(sql, connection))
                    {
                        command.Parameters.AddWithValue("@PhoneNumber", UserPhoneNumber);
                        command.Parameters.AddWithValue("@SongNumber", songNumber);
                        command.ExecuteNonQuery();
                    }

                    connection.Close();

                    
                    var song = AllSongs.FirstOrDefault(s => s.SongNumber == songNumber);
                    if (song != null)
                    {
                        FavoriteSongs.Add(song);
                        Console.WriteLine(String.Format("Added song {0} to favorites.", songNumber));
                    }
                    else
                    {
                        Console.WriteLine(String.Format("Song {0} not found in AllSongs.", songNumber));
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Failed to add song to favorites: " + ex.Message);
                }
            }
        }

        public List<SongData> SearchSongsBySinger(string keyword)
        {
            
            
            var keywordLower = keyword.ToLower();
            return AllSongs.Where(song => song.ArtistA.ToLower().Contains(keywordLower)
                                        || song.ArtistB.ToLower().Contains(keywordLower))
                        .ToList();
        }

        public List<SongData> SearchSongsByName(string keyword)
        {
            
            
            var keywordLower = keyword.ToLower();
            return AllSongs.Where(song => song.Song.ToLower().Contains(keywordLower)).ToList();
        }

        
        public SongData SearchSongByNumber(string songNumber)
        {
            
            foreach (var song in AllSongs)
            {
                if (song.SongNumber == songNumber)
                {
                    return song; 
                }
            }
            return null; 
        }

    }
}