using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Linq;
using tool;
using ct_terminal;
using Vlc.DotNet.Forms;

namespace Media
{
    public class MediaPlayer
    {
        MainForm mainForm;
        List<string> adlist { get; set; }
        List<string> imagelist { get; set; }
        PictureBox pictureBox1;
        VlcControl vlcControl;
        Label timeLab;
        Label dateLab;
        Label dateLab1;
        //广告播放线程
        Thread m_adsplay_thread;
        bool m_adsplay_condition;

        //图片播放线程
        Thread m_imageplay_thread;
        bool m_imageplay_condition;
        //时间显示线程
        Thread m_clockshow_thread;
        bool m_clockshow_condition;

        //显示天气线程
        Thread m_show_weather_thread;
        bool m_show_weather_condition;
        public MediaPlayer()
        {
            vlcControl = new Vlc.DotNet.Forms.VlcControl();
        }
        //播放器初始化、
        public void MediaPlayerInit(MainForm mainForm, ref PictureBox pictureBox1, ref VlcControl vlcControl, ref Label timeLab, ref Label dateLab, ref Label dateLab1)
        {

            this.mainForm = mainForm;
            this.pictureBox1 = pictureBox1;
            this.vlcControl = vlcControl;
            this.timeLab = timeLab;
            this.dateLab = dateLab;
            this.dateLab1 = dateLab1;
            //播放视频
            m_adsplay_thread = new Thread(adsplay_thread);
            m_adsplay_condition = false;
            //播放图片
            m_imageplay_thread = new Thread(imageplay_thread);
            m_imageplay_condition = false;
            //日期
            m_clockshow_thread = new Thread(clockshow_thread);
            m_clockshow_condition = false;
            //天气
            m_show_weather_thread = new Thread(show_weather_thread);
            m_show_weather_condition = false;
        }
        public void mediaplayer_run()
        {
            //启动四个线程
            m_adsplay_condition = true;
            m_adsplay_thread.Start();

            m_imageplay_condition = true;
            m_imageplay_thread.Start();

            m_clockshow_condition = true;
            m_clockshow_thread.Start();

            m_show_weather_condition = true;
            m_show_weather_thread.Start();
        }
        public void mediaplayer_uninit()
        {
            //关闭四个线程
            m_adsplay_condition = false ;
            m_clockshow_condition = false;
            m_imageplay_condition = false;
            m_show_weather_condition = false;

            m_adsplay_thread.Abort();
            m_imageplay_thread.Abort();
            m_clockshow_thread.Abort();
            m_show_weather_thread.Abort();

        }
        /// <summary>
        /// 循环播放视频
        /// </summary>
        private void adsplay_thread()
        {
            adlist = searchResource(@"Resource", "*.mp4");
            if (adlist.Count > 0)
            {
                while (m_adsplay_condition)
                {
                    for (int i = 0; i < adlist.Count; i++)
                    {
                        if (vlcControl.State == Vlc.DotNet.Core.Interops.Signatures.MediaStates.Ended ||
                            vlcControl.State == Vlc.DotNet.Core.Interops.Signatures.MediaStates.NothingSpecial)
                        {
                            mainForm.Invoke(new Action(() =>
                            {
                                vlcControl.Play(new FileInfo("Resource\\" + adlist[i]));
                            }));
                        }
                        Thread.Sleep(1000);
                    }
                }
                
            }

        }
        private void imageplay_thread()
        {
            imagelist = searchResource(@"Resource", "*.jpg");
            if (imagelist.Count > 0 && m_imageplay_condition)
            {
                for (int i = 0; i <= imagelist.Count; i++)
                {
                    if (!m_imageplay_condition)
                        return;
                    if (i == imagelist.Count)
                        i = 0;
                    try
                    {
                        //无法访问已释放的资源
                        mainForm.Invoke(new Action(() =>
                        {
                            using (FileStream fRead = new FileStream(System.AppDomain.CurrentDomain.BaseDirectory + "/Resource/" + imagelist[i], FileMode.OpenOrCreate, FileAccess.Read))
                            {
                                pictureBox1.Image = Image.FromStream(fRead);
                            }
                        }));
                    }
                    catch (Exception ex)
                    {
                    }
                    Thread.Sleep(1000);
                }
            }
        }
        private void clockshow_thread()
        {
            while (m_clockshow_condition)
            {
                try
                {
                    string time = System.DateTime.Now.ToString("HH:mm:ss");
                    string date = System.DateTime.Now.ToString("yyyy-MM-dd");
                    string[] weekdays = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
                    string week = weekdays[Convert.ToInt32(DateTime.Now.DayOfWeek)];
                    mainForm.Invoke(new Action(() =>
                    {
                        this.timeLab.Text = time;
                        this.dateLab.Text = date + " " + week;
                        this.dateLab1.Text = date + " " + week;

                    }));
                }
                catch { }
                Thread.Sleep(1000);
            }
        }


        /// <summary>
        /// 得到指定目录中的指定后缀文件
        /// </summary>
        /// <param name="directory">项目更路径下的资源文件夹</param>
        /// <param name="suffix">后缀（如：.jpg）</param>
        /// <returns></returns>
        private List<string> searchResource(string directory, string suffix)
        {
            DirectoryInfo dir = new DirectoryInfo(directory);
            FileInfo[] fileInfo = dir.GetFiles(suffix);
            List<string> list = new List<string>();
            foreach (FileInfo item in fileInfo)
            {
                //读取文件名，包括文件后缀
                list.Add(item.Name);
            }
            return list;
        }


        public void show_weather_thread()
        {
            while (m_show_weather_condition)
            {
                if (m_show_weather_condition)
                {
                    try
                    {
                        string url = "http://flash.weather.com.cn/wmaps/xml/china.xml";
                        WebClient MyWebClient = new WebClient();
                        Byte[] pageData = MyWebClient.DownloadData(url);
                        string pageHtml = Encoding.UTF8.GetString(pageData);
                        XDocument doc = XDocument.Parse(pageHtml);
                        var results = from ele in doc.Descendants("city") where ele.Attribute("cityname").Value.Equals(json_file_operation.Instance.read_json_string("city")) select ele;
                        foreach (var result in results)
                        {
                            string weatherStr = result.Attribute("stateDetailed").Value;
                            string temperature = result.Attribute("tem2").Value + "℃";
                            try
                            {
                                mainForm.Invoke(new Action(() =>
                                {
                                    mainForm.set_weatherLab_text("天气：" + weatherStr);
                                    mainForm.set_temperatureLab_text("气温：" + temperature);
                                }));
                            }
                            catch (Exception)
                            {

                            }
                        }
                    }
                    catch (WebException webEx)
                    {
                        Console.WriteLine(webEx.Message.ToString());
                    }
                }
                Thread.Sleep(60000);
            }


        }
    }
}
