using System.Data;
using DualScreenDemo;
namespace DBObj
{
    public class SQLManager
    {
        private MyDB db = new MyDB();
        public List<SongData> FavoriteSongs { get; private set; }
        //public bool IsUserLoggedIn { get; set; }  
        //public string UserPhoneNumber { get; set; }  
        public SQLManager()
        {
            FavoriteSongs = new List<SongData>();
        }
        /*
        public void AddNewUser(string phoneNumber)
        {
            
            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 List<SongData> SearchNewSongs()
        {
            string query = $"SELECT * FROM song_library_cache WHERE language_name = '國語' ORDER BY add_date DESC LIMIT {Utils.Env.GetInt("NewSongLimit", 100)};";
            return select_Mysql(query);
        }
        public List<SongData> SearchHotSongs(){
            string query= $"SELECT * FROM song_library_cache WHERE language_name = '國語' ORDER BY song_counts DESC LIMIT {Utils.Env.GetInt("HotSongLimit", 100)};";
            return select_Mysql(query);
        }
        public List<SongData> SearchSongsBySinger(string keyword)
        {
            Console.WriteLine("keyword : " + keyword);
            var keywordLower = keyword.ToLower();
            string query = $"SELECT * FROM song_library_cache WHERE artistA LIKE '%{keywordLower}%' OR artistB LIKE'%{keywordLower}%'ORDER BY song_counts DESC;";
            return select_Mysql(query);
        }
        public List<SongData> SearchSongsByName(string keyword)
        {
            string query = $"SELECT * FROM song_library_cache WHERE LOWER(song_name) LIKE CONCAT('%', LOWER('{keyword}'), '%');";
            return select_Mysql(query);
        }        
        public SongData SearchSongByNumber(string songNumber)
        {
            string query = $"SELECT * FROM song_library_cache WHERE song_id = '{songNumber}';";
            var searchResults =select_Mysql(query);
            return  searchResults.FirstOrDefault();
        }
        private  List<SongData> select_Mysql(string query)
        {
            List<SongData> searchResults = new List<SongData>();
            Console.WriteLine(query);
            using (var db = new MyDB())
            {
                if (db.open(query, null)) {
                    while (db.Read()){
                       searchResults.Add(new SongData(
                            db.Field<string>("song_id"),
                            db.Field<string>("song_name"),
                            db.Field<string>("artistA"),
                            db.Field<string>("artistB"),
                            db.Field<string>("song_filename"),
                            db.Field<string>("artistA_simplified"),
                            db.Field<string>("artistB_simplified"),
                            db.Field<string>("song_simplified"),
                            db.Field<int>("vocal")
                        ));
                    }
                }
               
                Console.WriteLine($"查詢到 {searchResults.Count} 筆資料。");
            }

            return searchResults;
        }

    }
}