using BLL;
using DAL;
using Helper;
using Model;
using Sunny.UI;
using SunnyMusic.Properties;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using TagLib;
namespace  ZSMusic.Winform
{
    /// <summary>
    /// 二次封装适用于表示层的帮助类
    /// </summary>
    public class MusicHelper
    {
        /// <summary>
        /// 主窗体对象
        /// </summary>
        public static FrmMain MainForm { get; set; }
        /// <summary>
        /// 是否在线解析
        /// </summary>
        public static bool Online
        {
            get { return Settings.Default.在线解析; }
            set
            {
                Settings.Default.在线解析 = value;
                MainForm.LoadSources();
            }
        }
        public static int Num
        {
            get { return Settings.Default.每页显示数量; }
            set { Settings.Default.每页显示数量 = value; }
        }
        public static double Similar
        {
            get { return Settings.Default.重新查找精确度; }
            set { Settings.Default.重新查找精确度 = value; }
        }
        public static string Ip
        {
            get { return Settings.Default.服务器地址; }
            set { Settings.Default.服务器地址 = value; }
        }
        public static string Format
        {
            get { return Settings.Default.文件命名格式; }
            set { Settings.Default.文件命名格式 = value; }
        }
        public static string Path
        {
            get { return Settings.Default.下载路径; }
            set { Settings.Default.下载路径 = value; }
        }
        /// <summary>
        /// 业务逻辑层对象
        /// </summary>
        public MusicBLL Bll { get; set; }
        /// <summary>
        /// 实体对象
        /// </summary>
        public Music MusicModel { get; set; }
        /// <summary>
        /// 歌手集合
        /// </summary>
        public string[] Artists
        {
            get
            {
                if (MusicModel.Artist.Contains(","))
                {
                    return MusicModel.Artist.Split(',');
                }
                else if (MusicModel.Artist.Contains("&")) { return MusicModel.Artist.Split('&'); }
                else { return new string[] { MusicModel.Artist }; }
            }
        }
        public void GetDataAsync()
        {
            Thread t = new Thread(Method0);
            t.IsBackground = true;
            t.Name = "预加载:" + MusicModel;
            t.Start();
        }
        private void Method0()
        {
            GetData();
        }
        public bool GetData()
        {
            try
            {
                if (Online)
                {
                    string url = string.Format(
                    "http://" + Ip + "/getdata.aspx?source={0}&id={1}&name={2}&artist={3}&album={4}&picid={5}",
                    MusicModel.Source, MusicModel.Id, MusicModel.Name, MusicModel.Artist, MusicModel.Album, MusicModel.PicId);
                    string src = HttpHelper.Get(url);
                    MusicModel = Music.JsonToList(src)[0];
                    return HttpHelper.CheckUri(MusicModel.Url);
                }
                else
                {
                    return Bll.GetData(MusicModel);
                }
            }
            catch (Exception)
            { }
            finally { GC.Collect(); }
            return false;
        }
        /// <summary>
        /// 搜索
        /// </summary>
        /// <param name="args">搜索参数</param>
        /// <returns></returns>
        public static List<Music> Search(SearchArgs args)
        {
            List<Music> result = new List<Music>();
            if (Online)
            {
                string src = HttpHelper.Get(string.Format(
                "http://" + Ip + "/search.aspx?source={0}&word={1}&page={2}&num={3}"
                , args.Source, args.Word, args.Page, Num)).Trim();
                result.AddRange(Music.JsonToList(src));
            }
            else
            {
                MusicBLL bll = new MusicBLL(args.Source);
                result.AddRange(bll.Search(args.Word, args.Page, 30));
            }
            return result;
        }
        /// <summary>
        /// 下载歌曲
        /// </summary>
        /// <param name="path">路径</param>
        public virtual void Download()
        {
            MusicModel.ToString();
            try
            {
                string fmt = "mp3";
                string[] fmts = { "mp3", "m4a", "mp4", "aac", "mid", "ogg", "wav", "ape", "flac", "wma", "amr", "swf" };
                foreach (var item in fmts)
                {
                    if (MusicModel.Url.Contains(item))
                    {
                        fmt = item;
                        break;
                    }
                }
                string filepath = string.Format("{0}\\" + Format + ".{3}", Path, MusicModel.Artist, MusicModel.Name, fmt).Replace("\\\\", "\\");
                if (System.IO.File.Exists(filepath))
                {
                    if (!Cover)
                        if (!Sunny.UI.UIMessageDialog.ShowMessageDialog("文件已存在,是否覆盖?", MusicModel.ToString(), true, UIStyle.Custom))
                        { return; }
                }
                HttpHelper.Down(filepath, MusicModel.Url);
                ChangeID3(filepath);
                MainForm.notify.ShowBalloonTip(3000, "下载成功",
                string.Format("{0} - {1}", MusicModel.Artist, MusicModel.Name)
                , ToolTipIcon.Info);

                if (Settings.Default.下载歌词 && MusicModel.Lrc != null)
                {
                    MusicModel.GetLrc().Save(string.Format("{0}\\" + Format + ".lrc", Path, MusicModel.Artist, MusicModel.Name), Encoding.Default);
                }
                if (Settings.Default.下载封面 && MusicModel.PicUrl != null)
                {
                    Image pic = ImageHelper.GetImage(MusicModel.PicUrl);
                    if (pic != null)
                        pic.Save(string.Format("{0}\\" + Format + ".jpg", Path, MusicModel.Artist, MusicModel.Name), ImageFormat.Jpeg);
                }
            }
            catch (Exception ex)
            {
                MainForm.notify.ShowBalloonTip(3000, "下载失败",
                string.Format("{0} - {1}\n{2}", MusicModel.Artist, MusicModel.Name, ex.Message)
                , ToolTipIcon.Error);
            }
        }
        /// <summary>
        /// 修改Id3信息
        /// </summary>
        /// <param name="filepath">文件路径</param>
        public void ChangeID3(string filepath)
        {
            string picpath = Environment.CurrentDirectory + "\\" + "temp.jpg";
            try
            {
                var file = TagLib.File.Create(filepath);
                file.Tag.Title = MusicModel.Name;
                file.Tag.Artists = Artists;
                if (MusicModel.Album != null)
                { file.Tag.Album = MusicModel.Album; }
                if (MusicModel.Lrc != null)
                { file.Tag.Lyrics = MusicModel.Lrc; }
                file.Tag.Comment = "遗憾迟香音乐助手";
                file.Save();
                if (MusicModel.PicUrl != null)
                {
                    Image pic = ImageHelper.GetImage(MusicModel.PicUrl);
                    pic.Save(picpath, ImageFormat.Jpeg);
                    TagLib.Id3v2.AttachedPictureFrame attachedPictureFrame = new TagLib.Id3v2.AttachedPictureFrame(new Picture(picpath))
                    {
                        MimeType = "image/jpeg",
                        Description = "YA.jpg",
                        Type = PictureType.FrontCover
                    };
                    file.Tag.Pictures = new TagLib.IPicture[]
					{
						attachedPictureFrame
					};
                }
                file.Save();
            }
            catch (Exception)
            {

            }
            finally { System.IO.File.Delete(picpath); }
        }
        /// <summary>
        /// 使用单独线程下载歌曲
        /// </summary>
        /// <param name="path">路径</param>
        public virtual void DownLoadAsync(string path, NotifyIcon form = null)
        {
            Thread t = new Thread(Download);
            t.Start();
        }

        public MusicHelper(Music m)
        {
            MusicModel = m;
            Bll = new MusicBLL(m.Source);
        }
        public MusicHelper() { }
        public static Music ReSearch(Music m, double similar)
        {
            if (Online)
            {
                string src = HttpHelper.Get(string.Format(
                "http://" + Ip + "/research.aspx?name={0}&artist={1}&similar={2}"
                , m.Name, m.Artist, Similar));
                m = Music.JsonToList(src)[0];
                if (!HttpHelper.CheckUri(m.Url))
                { throw new Exception("对不起,未能找到你想要的歌曲资源"); }
            }
            else
            {
                MusicBLL bll = new MusicBLL();
                return bll.ReSearch(m, 0.75);
            }
            return m;
        }

        public bool Cover { get; set; }

    }
}
