using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using WeifenLuo.WinFormsUI.Docking;
using System.Text.RegularExpressions;
using pcmp.Setting;
using System.IO;

namespace pcmp.Forms
{
    public partial class FormChannelInfo : DockContent
    {
        public event EventHandler<ThrowUrlEventArgs> OnPlayChannel;
        public event EventHandler<ThrowUrlEventArgs> OnNewWindow;

        private string htmltemp = string.Empty;
        private string loadfilepath = string.Empty;
        private Channel channel = null;

        public FormChannelInfo()
        {
            InitializeComponent();
            webBrowser.DocumentText = string.Empty;
            Application.Idle += new EventHandler(Application_Idle);
        }

        void Application_Idle(object sender, EventArgs e)
        {
            Application.Idle -= new EventHandler(Application_Idle);
            LoadHtmlTemplate();
        }

        private void LoadHtmlTemplate()
        {
            switch (this.DockState)
            {
                case DockState.DockBottom:
                case DockState.DockBottomAutoHide:
                case DockState.DockTop:
                case DockState.DockTopAutoHide:
                    if (File.Exists(Path.Combine(Settings.GeneralSetting.TemplatePath, "ChannelInfoH.html")))
                    {
                        loadfilepath = Path.Combine(Settings.GeneralSetting.TemplatePath, "ChannelInfoH.html");
                        htmltemp = File.ReadAllText(loadfilepath);
                    }
                    else if (File.Exists(Path.Combine(Settings.GeneralSetting.TemplatePath, "infoH.html")))
                    {
                        loadfilepath = Path.Combine(Settings.GeneralSetting.TemplatePath, "infoH.html");
                        htmltemp = File.ReadAllText(loadfilepath);
                    }
                    else htmltemp = "ChannelInfoH.html(or infoH.html) do not exist in \"" + Settings.GeneralSetting.TemplatePath + "\".";
                    break;
                case DockState.DockLeft:
                case DockState.DockLeftAutoHide:
                case DockState.DockRight:
                case DockState.DockRightAutoHide:
                    if (File.Exists(Path.Combine(Settings.GeneralSetting.TemplatePath, "ChannelInfoV.html")))
                    {
                        loadfilepath = Path.Combine(Settings.GeneralSetting.TemplatePath, "ChannelInfoV.html");
                        htmltemp = File.ReadAllText(loadfilepath);
                    }
                    else if (File.Exists(Path.Combine(Settings.GeneralSetting.TemplatePath, "infoV.html")))
                    {
                        loadfilepath = Path.Combine(Settings.GeneralSetting.TemplatePath, "infoV.html");
                        htmltemp = File.ReadAllText(loadfilepath);
                    }
                    else htmltemp = "ChannelInfoV.html(or infoV.html) do not exist in \"" + Settings.GeneralSetting.TemplatePath + "\".";
                    break;
                default:
                    break;
            }
        }

        public void ShowChannelInfo(ListViewItem item)
        {
            channel = (Channel)item.Tag;
            string html = Common.ReplaceHtml(htmltemp, channel, Settings.GeneralSetting.TemplatePath);
            SetDocumentText(html);
        }

        /// <summary>
        /// WebBrowserのテキストを変更する
        /// </summary>
        /// <param name="html">WebBrowserに入れるHTML</param>
        private void SetDocumentText(string html)
        {
            // htmlがnullだった場合終了
            if (html == null) return;
            webBrowser.TabStop = false;
            webBrowser.Document.OpenNew(false);
            webBrowser.Document.Write(html);
        }

        private void webBrowser_StartNavigate(object sender, ExtendedWebBrowser2.BrowserExtendedNavigatingEventArgs e)
        {
            // チャンネルの情報を表示する場合は無視
            if (e.Url.AbsoluteUri == "about:blank") return;
            if (e.Url.AbsoluteUri.Contains(new Uri(loadfilepath).AbsoluteUri)) return;

            e.Cancel = true;
            Regex regex = new Regex(@"http://([^:]+):([0-9]+)/pls/([A-Z0-9]{32})");
            Match m = regex.Match(e.Url.AbsoluteUri);
            // 再生する
            if (m.Success)
            {
                if (OnPlayChannel != null) OnPlayChannel(null, new ThrowUrlEventArgs(e.Url.AbsoluteUri, channel));
            }
            else // ブラウザで開く
            {
                if (Setting.Settings.GeneralSetting.UseBrowser2ch)
                {
                    try
                    {
                        Regex regex2ch = new Regex(Settings.GeneralSetting.Regex2chUrl);
                        if (regex2ch.IsMatch(e.Url.AbsoluteUri))
                        {
                            Common.StartProcess(Settings.GeneralSetting.Browser2chPath, e.Url.AbsoluteUri);
                            return;
                        }
                    }
                    catch (ArgumentException) { }
                }

                if (Settings.GeneralSetting.UseOtherBrowser)
                {
                    Common.StartProcess(Settings.GeneralSetting.BrowserPath, e.Url.AbsoluteUri);
                }
                else
                {
                    if (OnNewWindow != null)
                        OnNewWindow(null, new ThrowUrlEventArgs(e.Url.AbsoluteUri, channel));
                }
            }
        }

        private void webBrowser_DownloadComplete(object sender, EventArgs e)
        {
            if (webBrowser.Document != null)
            {
                // Subscribe to the Error event
                webBrowser.Document.Window.Error += new HtmlElementErrorEventHandler(Window_Error);
            }
        }

        private void Window_Error(object sender, HtmlElementErrorEventArgs e)
        {
            e.Handled = true;
        }

        internal void ApplySetting()
        {
        }
    }

    public class ThrowUrlEventArgs : EventArgs
    {
        public ThrowUrlEventArgs(string url, Channel channel)
        {
            Url = url;
            Channel = channel;
        }

        public string Url { get; set; }
        public Channel Channel { get; set; }
    }
}