using System;
using MaterialSkin;
using MaterialSkin.Controls;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using Herse.Models;
using System.IO.Compression;

namespace KaraokePlayer
{
    public partial class MainForm : MaterialForm
    {
        HerseDb db = new HerseDb();
        private readonly MaterialSkinManager _materialSkinManager;
        private List<Song> _fileList;
        private Song currentSong = null;
        private KaraokeVideoPlayer currentPlayer = null;
        public MainForm()
        {
            InitializeComponent();
            karaokeCDGPlayer.setup(true, true);
            karaokeMP4Player.setup(false, true);
            karaokeCDGPlayer.songEndedHandler += new KaraokePlayer.KaraokeVideoPlayer.SongEndedEventHandler(this.karaokePlayerSongEnded);
            karaokeMP4Player.songEndedHandler += new KaraokePlayer.KaraokeVideoPlayer.SongEndedEventHandler(this.karaokePlayerSongEnded);
            // Initialize MaterialSkinManager
            _materialSkinManager = MaterialSkinManager.Instance;
            _materialSkinManager.AddFormToManage(this);
            //_materialSkinManager.Theme = new DarkTheme();
            _materialSkinManager.ColorScheme = new ColorScheme(Primary.Green600, Primary.Green700, Primary.Green200, Accent.Red100, TextShade.WHITE);
        }

        private void materialRaisedButton1_Click(object sender, System.EventArgs e)
        {
            playSelectedFile();
        }

        private void btnBrowse_Click(object sender, EventArgs e)
        {
            if (browseDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                var files = GetFiles(browseDialog.SelectedPath, "*.cdg|*.mp4|*.zip", searchOption: System.IO.SearchOption.AllDirectories);
                var filtered = files.Where(f => f.Length < 248).ToList();

                _fileList = filtered.Select(file => CreateSongForPath(file)).ToList();
                materialListBox1.DataSource = _fileList;
                materialListBox1.DisplayMember = "Description";

            }
        }

        private void materialListBox1_MouseDoubleClick(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            int index = this.materialListBox1.IndexFromPoint(e.Location);
            if (index != System.Windows.Forms.ListBox.NoMatches)
            {
                playSelectedFile();
            }
        }

        private void materialSingleLineTextField1_TextChanged(object sender, EventArgs e)
        {
            materialListBox1.DataSource = _fileList.Where(
                file => Regex.IsMatch(file.FullPath, materialSingleLineTextField1.Text, RegexOptions.IgnoreCase)).ToList();
        }

        public static string[] GetFiles(string path, string searchPattern, SearchOption searchOption)
        {
            string[] searchPatterns = searchPattern.Split('|');
            List<string> files = new List<string>();
            foreach (string sp in searchPatterns)
                files.AddRange(System.IO.Directory.GetFiles(path, sp, searchOption));
            files.Sort();
            return files.ToArray();
        }

        public void playSelectedFile()
        {
            Song file = (Song)materialListBox1.SelectedItem;
            currentSong = file;
            if (file.Extension.ToLower() == "cdg")
            {
                currentPlayer = karaokeCDGPlayer;
                karaokeCDGPlayer.Play(new Uri(Path.ChangeExtension(file.FullPath, ".mp3")));
                karaokeCDGPlayer.Visible = true;
                karaokeMP4Player.Visible = false;
                karaokeMP4Player.Stop();
            }
            else if (file.Extension.ToLower() == "zip")
            {
                string playPath = null;
                string extractPath = Path.Combine(Directory.GetCurrentDirectory(), "temp");
                DeleteDirectory(extractPath);
                Directory.CreateDirectory(extractPath);
                using (ZipArchive archive = ZipFile.OpenRead(file.FullPath))
                {
                    foreach (ZipArchiveEntry entry in archive.Entries)
                    {
                        if (entry.FullName.EndsWith(".mp3", StringComparison.OrdinalIgnoreCase))
                        {
                            playPath = Path.Combine(extractPath, entry.FullName);
                        }
                        entry.ExtractToFile(Path.Combine(extractPath, entry.FullName));
                    }
                }
                if (!string.IsNullOrEmpty(playPath))
                {
                    currentPlayer = karaokeCDGPlayer;
                    karaokeCDGPlayer.Play(new Uri(playPath));
                    karaokeCDGPlayer.Visible = true;
                    karaokeMP4Player.Visible = false;
                    karaokeMP4Player.Stop();
                }
            }
            else {
                currentPlayer = karaokeMP4Player;
                karaokeMP4Player.Play(new Uri(file.FullPath));
                karaokeMP4Player.Visible = true;
                karaokeCDGPlayer.Visible = false;
                karaokeCDGPlayer.Stop();
            }
        }

        public void karaokePlayerSongEnded(object sender, EventArgs e)
        {
            //here
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            if (currentPlayer == null) return;
            currentPlayer.Stop();
        }

        private Song CreateSongForPath(string path)
        {
            Song song = new Song(path);
            return song;
        }

        public void DeleteDirectory(string target_dir)
        {
            if (!Directory.Exists(target_dir)) { return; }
            string[] files = Directory.GetFiles(target_dir);
            string[] dirs = Directory.GetDirectories(target_dir);

            foreach (string file in files)
            {
                File.SetAttributes(file, FileAttributes.Normal);
                File.Delete(file);
            }

            foreach (string dir in dirs)
            {
                DeleteDirectory(dir);
            }

            Directory.Delete(target_dir, false);
        }

        private void btnPlayQueue_Click(object sender, EventArgs e)
        {
            _fileList = db.Songs.Where(s => s.Id > 0).OrderBy(s=>s.Artist).ThenBy(s=>s.Title).ToList();
            materialListBox1.DataSource = _fileList;
            materialListBox1.DisplayMember = "Description";
        }
    }
}
