using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ZSMusic.Model;
using System.IO;
using Helper;
using System.Drawing;
using Win32Helper;
using System.Drawing.Imaging;
using ZSMusic.BLLEX;
using System.Configuration;
using System.Runtime.InteropServices;
using System.Diagnostics;

namespace ZSMusic.Downloader
{
    public class Program
    {
        public static List<Music> ErrList { get; set; }
        public static List<Exception> ErrMessage { get; set; }
        static void Main(string[] args)
        {
            new ConsoleCtrl();
            ErrList = new List<Music>();
            ErrMessage = new List<Exception>();
            string path = ConfigurationManager.AppSettings["path"];
            string json = File.ReadAllText("temp.json", Encoding.Default);
            List<Music> list = JsonConvert.DeserializeObject<List<Music>>(json);
            bool pic = ConfigurationManager.AppSettings["pic"].ToLower() == "true";
            bool lrc = ConfigurationManager.AppSettings["lrc"].ToLower() == "true";
            string format = ConfigurationManager.AppSettings["format"];
            DownLoad(path, list, pic, lrc, format);
            Console.Title = "下载完成";
            if (ErrList.Count == 0)
            { return; }
            Console.WriteLine("{0}首歌下载失败", ErrList.Count);
            for (int i = 0; i < ErrList.Count; i++)
            {
                Console.WriteLine("{0}\t{1}", ErrList[i], ErrMessage[i].Message);
            }
            Console.WriteLine("按回车键重新下载");
            ConsoleKeyInfo key = Console.ReadKey();
            if (key.Key == ConsoleKey.Enter)
            {
                File.WriteAllText("temp.json", JsonConvert.SerializeObject(ErrList), Encoding.Default);
                Process.Start("ZSMusic.Downloader.exe");
            }
        }

        public static void DownLoad(string path, List<Music> list, bool pic, bool lrc, string format = "{1} - {2}")
        {
            for (int i = 0; i < list.Count; i++)
            {
                Console.Title = string.Format("正在下载中{0}/{1} 按Ctrl+C终止", i + 1, list.Count);
                Music m = list[i];
                Console.WriteLine("正在下载中:\t{0}", m);
                DownLoad(path, m, pic, lrc, format);
            }
        }

        public static void DownLoad(string path, Music m, bool pic, bool lrc, string format = "{1} - {2}")
        {
            m.ToString();
            try
            {
                if (!HttpHelper.CheckUri(m.Url))
                {
                    m = MusicHelper.GetData(m);
                }
                if (!HttpHelper.CheckUri(m.Url))
                {
                    Console.WriteLine("未能解析下载地址正在重新查找:\t{0}", m);
                    m = MusicHelper.ReSearch(m);
                }
                string fmt = "mp3";
                string[] fmts = { "mp3", "m4a", "mp4", "aac", "mid", "ogg", "wav", "ape", "flac", "wma", "amr", "swf" };
                foreach (var item in fmts)
                {
                    if (m.Url.Contains(item))
                    {
                        fmt = item;
                        break;
                    }
                }
                string filepath = string.Format("{0}\\" + format + ".{3}", path, m.Artist, m.Name, fmt).Replace("\\\\", "\\");
                //if (System.IO.File.Exists(filepath))
                //{
                //    if (!Cover)
                //        if (!Sunny.UI.UIMessageDialog.ShowMessageDialog("文件已存在,是否覆盖?", m.ToString(), true, UIStyle.Custom))
                //        { return; }
                //}
                HttpHelper.Down(filepath, m.Url);
                ChangeID3(m, filepath);
                Console.WriteLine("下载成功{0} - {1}", m.Artist, m.Name);

                if (lrc && !string.IsNullOrWhiteSpace(m.Lrc))
                {
                    Lyric.Parse(m.Lrc).Save(string.Format("{0}\\" + format + ".lrc", path, m.Artist, m.Name), Encoding.Default);
                }
                if (pic && m.PicUrl != null)
                {
                    Image img = ImageHelper.GetImage(m.PicUrl);
                    if (img != null)
                        img.Save(string.Format("{0}\\" + format + ".jpg", path, m.Artist, m.Name), ImageFormat.Jpeg);
                }
            }
            catch (Exception ex)
            {
                ErrList.Add(m);
                ErrMessage.Add(ex);
            }
        }
        /// <summary>
        /// 修改Id3信息
        /// </summary>
        /// <param name="filepath">文件路径</param>
        public static void ChangeID3(Music m, string filepath)
        {
            string picpath = string.Format("{0}\\{1}.jpg", Environment.CurrentDirectory, m.GetHashCode());// Environment.CurrentDirectory + "\\" + "temp.jpg";
            try
            {
                var file = TagLib.File.Create(filepath);
                file.Tag.Title = m.Name;
                file.Tag.Artists = GetArtists(m.Artist);
                if (m.Album != null)
                { file.Tag.Album = m.Album; }
                if (m.Lrc != null)
                { file.Tag.Lyrics = m.Lrc; }
                file.Tag.Comment = "ZSMusic";
                file.Save();
                if (m.PicUrl != null)
                {
                    Image pic = ImageHelper.GetImage(m.PicUrl);
                    pic.Save(picpath, ImageFormat.Jpeg);
                    TagLib.Id3v2.AttachedPictureFrame attachedPictureFrame = new TagLib.Id3v2.AttachedPictureFrame(new TagLib.Picture(picpath))
                    {
                        MimeType = "image/jpeg",
                        Description = "YA.jpg",
                        Type = TagLib.PictureType.FrontCover
                    };
                    file.Tag.Pictures = new TagLib.IPicture[]
					{
						attachedPictureFrame
					};
                }
                file.Save();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally { System.IO.File.Delete(picpath); }
        }

        /// <summary>
        /// 歌手集合
        /// </summary>
        public static string[] GetArtists(string artist)
        {
            if (artist.Contains(","))
            {
                return artist.Split(',');
            }
            else if (artist.Contains("&")) { return artist.Split('&'); }
            else { return new string[] { artist }; }
        }



    }
    public class ConsoleCtrl
    {
        [DllImport("User32.dll", EntryPoint = "FindWindow")]
        private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
        [DllImport("user32.dll", EntryPoint = "FindWindowEx")]   //找子窗体   
        private static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);
        [DllImport("User32.dll", EntryPoint = "SendMessage")]   //用于发送信息给窗体   
        private static extern int SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, string lParam);
        [DllImport("User32.dll", EntryPoint = "ShowWindow")]   //
        private static extern bool ShowWindow(IntPtr hWnd, int type);

        public ConsoleCtrl()
        {
            Console.Title = "个人工作平台";
            IntPtr ParenthWnd = new IntPtr(0);
            IntPtr et = new IntPtr(0);
            ParenthWnd = FindWindow(null, "个人工作平台");

            ShowWindow(ParenthWnd, 2);//隐藏本dos窗体, 0: 后台执行；1:正常启动；2:最小化到任务栏；3:最大化
        }
    }
}
