//ライセンス情報はAgeOnフォルダのLISENCEフォルダを参照してください

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Threading;

using nispi.Menu;
using nispi.controlclass;

namespace nispi
{
    class MyWebBrowser : System.Windows.Forms.WebBrowser
    {
        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams parms = base.CreateParams;
                parms.Style |= 0x800000;  // Turn on WS_BORDER
                return parms;
            }
        }
    }

    static class PopUpManager
    {
        public static int lastTime;
        public static string openNum;
        public static string openDatUrl;
        public static bool openFlag;

        public static void Setup()
        {
            lastTime = 0;
            openNum = "";
            openDatUrl = "";
            openFlag = false;
        }
    }

    class BrowserParts:ControlBase
    {
        public MyWebBrowser control = new MyWebBrowser();

        private ThreadViewCommon threadView;
        //マウス押下時に得る文字列
        string mouseDownText = "";
        
        public bool nonTextMenuOn;
        public bool textMenuOn;

        public FormParts ownerForm;

        public Point mouseDownPoint;

        public string type = "";

        public BrowserParts()
        {
            control.Location = new Point(0, 27);
            control.Name = "webBrowser1";
            control.TabIndex = 0;
            control.ScrollBarsEnabled = true;
            //control.Font = new Font("Meiryo UI", 10.75F, FontStyle.Regular, GraphicsUnit.Point, ((byte)(128)));
            control.ScriptErrorsSuppressed = true;

            control.IsWebBrowserContextMenuEnabled = false;

            this.BrowserClear();
            control.Document.Window.Name = "Basic";

            control.Document.MouseMove += new HtmlElementEventHandler(Document_MouseMove);
            control.Document.MouseDown += new HtmlElementEventHandler(Document_MouseDown);
            control.Document.MouseUp += new HtmlElementEventHandler(Document_MouseUp);
            this.controlBase = (System.Windows.Forms.Control)control;
            //control.PreviewKeyDown += new PreviewKeyDownEventHandler(control_PreviewKeyDownEvent);
        }


        public void ResetControl()
        {
            //this.control.Anchor = AnchorStyles.None;
            //this.control.Dock = DockStyle.None;
            //this.Location = new Point(1, 1);
            //this.Size = new Size(1, 1);
        }
        public void SetDockFill()
        {
            this.control.Dock = DockStyle.Fill;
        }
        public bool CheckConsistency()
        {
            try
            {
                int index = Const.form.threadListTabControlParts.SelectedIndex;
                this.threadView = MainFormConst.threadListTabMain.viewList[index];
                return true;
            }
            catch
            {
                return false;
            }
        }

        //ドキュメント
        public HtmlDocument Document
        {
            /*set
            {
                this.control.Document = value;
            }*/
            get
            {
                return this.control.Document;
            }
        }
        public string Document_Window_Name
        {
            set
            {
                this.control.Document.Window.Name = value;
            }
            get
            {
                return this.control.Document.Window.Name;
            }
        }
        public Size Document_Body_ScrollRectangle_Size
        {
            set
            {
                //this.control.Document.Body.ScrollRectangle.Size = value;
            }
            get
            {
                return this.control.Document.Body.ScrollRectangle.Size;
            }
        }
        public bool AllowNavigation
        {
            set
            {
                this.control.AllowNavigation = value;
            }
            get
            {
                return this.control.AllowNavigation;
            }
        }
        public void BrowserClear()
        {
            try
            {
                if (control.Document != null)
                {
                    //control.Navigate("about:blank");
                    //HtmlDocument doc = this.control.Document;
                   // doc.Write(String.Empty);
                    //control.Document.Write(String.Empty);
                    control.Document.OpenNew(false);
                }
                else
                {
                    control.Navigate("about:blank");
                    //control.Document.Write(String.Empty);
                }
            }
            catch { ;}
        }

        public void Stop()
        {
            this.control.Stop();
        }
        //ドキュメントを開く
        public void OpenNew(bool type)
        {
            this.control.Document.OpenNew(type);
        }
        public void Navigate(string text)
        {
            this.control.Navigate(text);
        }
        public void Write(string text)
        {
            this.control.Document.Write(text);
        }
        public Point GetScrollRectangle()
        {
            HtmlElement body = this.control.Document.Body;
            if (body == null)
                return new Point(0, 0);
            Point scrollpos = new Point(body.ScrollRectangle.X, body.ScrollRectangle.Y);
            return scrollpos;
        }
        public ThreadViewCommon threadViewProperty
        {
            set
            {
                this.threadView = value;
            }
        }

        #region MouseMove
        //ドキュメント上をマウスが動いたとき。ポップアップ等
        public void Document_MouseMove(object sender, HtmlElementEventArgs e)
        {
            if (CheckConsistency() == false)
                return;

            HtmlDocument htmlDocument = (HtmlDocument)sender;

            //条件によりポップアップウィンドウを開く
            HtmlElement overElement = htmlDocument.GetElementFromPoint(e.MousePosition);
            string text = "";
            string href = "";
            HtmlUtil.GetClickTagInfo(overElement, ref href, ref text);

            //ポップアップウィンドウのコントロール場合
            if (true == htmlDocument.Window.Name.Equals("PopUp"))
            {
                GetFocus(htmlDocument);
            }
            else
            {
                if (htmlDocument.Focused == false)
                {
                    //ポップアップウィンドウがある場合は無条件で消す
                    if (MainFormConst.htmlPopUpWindowWidget.popUpList.Count > 0)
                    {
                        /* レス番号 */
                        if (0 == href.IndexOf("javascript:void(0);#res", 0))
                        {
                            string number = text.Remove(0, 2);
                            string datUrl = href.Remove(0, 23 + number.Length + 1);
                            if ((false == PopUpManager.openNum.Equals(number)) || (number.Equals("0") == true))
                            {
                                MainFormConst.htmlPopUpWindowWidget.RemoveAllPopUp();
                                GetFocus(htmlDocument);
                            }
                        }
                        else if (href.Length == 0)
                        {
                            MainFormConst.htmlPopUpWindowWidget.RemoveAllPopUp();
                            GetFocus(htmlDocument);
                        }
                    }
                    //ポップアップウィンドウが無い時。
                    else
                    {
                        GetFocus(htmlDocument);
                    }
                }
            }

            if ((text != null) && (text.Length > 1))
            {
                System.Diagnostics.Debug.WriteLine("focus4");
                //アンカーの場合
                if (text.IndexOf(">>") == 0)
                {
                    /* レス番号 */
                    if (0 == href.IndexOf("javascript:void(0);#res", 0))
                    {
                        string number = text.Remove(0, 2);
                        string datUrl = href.Remove(0, 23 + number.Length + 1);//　1 == "#"

                        if (true == PopUpManager.openNum.Equals(number))
                        {
                        }
                        else
                        {
                            PopUpManager.openDatUrl = datUrl;
                            PopUpManager.openNum = number;
                            PopUpManager.openFlag = true;
                            PopUpManager.lastTime = System.Environment.TickCount & int.MaxValue;

                            MainFormConst.PopUpWindow(Cursor.Position, threadView, datUrl, number);
                        }
                    }
                }
                else if (text.IndexOf("ID") == 0)
                {
                    /* レス番号 */
                    if (0 == href.IndexOf("javascript:void(0);#ID:", 0))
                    {
                        string id = text;
                        string datUrl = href.Remove(0, 23 + id.Length + 1);

                        if (true == PopUpManager.openNum.Equals(id))
                        {
                        }
                        else
                        {
                            PopUpManager.openNum = id;
                            MainFormConst.PopUpWindow(Cursor.Position, threadView, datUrl, id, "idFromID");
                        }
                    }
                }
                else if (text.IndexOf("ﾚｽ") == 0)
                {
                    /* レス番号 */
                    if (0 == href.IndexOf("javascript:void(0);#POPNUM:", 0))
                    {
                        string temp = href.Remove(0, 27);
                        string[] temp2 = temp.Split('#');
                        string number = temp2[1];
                        string datUrl = temp2[2];

                        if (true == PopUpManager.openNum.Equals(number))
                        {
                        }
                        else
                        {
                            PopUpManager.openNum = number;
                            MainFormConst.PopUpWindow(Cursor.Position, threadView, datUrl, number, "POPNUM");
                        }
                    }
                }
                else if (text.IndexOf("あぼんを表示") == 0)
                {
                    /* レス番号 */
                    if (0 == href.IndexOf("javascript:void(0);#ABON:", 0))
                    {
                        string temp = href.Remove(0, 25);
                        string[] temp2 = temp.Split('#');
                        string number = temp2[1];
                        string datUrl = temp2[2];

                        if (true == PopUpManager.openNum.Equals(number))
                        {
                        }
                        else
                        {
                            PopUpManager.openNum = number;
                            MainFormConst.PopUpWindow(Cursor.Position, threadView, datUrl, number, "ABON");
                        }
                    }
                }

                else if ((text.IndexOf("2BP") == 0) ||
                    (text.IndexOf("BRZ") == 0) ||
                    (text.IndexOf("PLT") == 0) ||
                    (text.IndexOf("DIA") == 0) ||
                    (text.IndexOf("S★") == 0))
                {
                    if (0 == href.IndexOf("javascript:void(0);#BE:", 0))
                    {
                        string be = href.Split('#')[1].Remove(0, 3);
                        string datUrl = href.Remove(0, 23 + be.Length + 1);

                        if (true == PopUpManager.openNum.Equals(be))
                        {
                        }
                        else
                        {
                            PopUpManager.openNum = be;
                            MainFormConst.PopUpWindow(Cursor.Position, threadView, datUrl, be, "BE");
                        }
                    }
                }
            }
            else
            {
                PopUpManager.openNum = "0";
            }
        }
        public void GetFocus(HtmlDocument htmlDocument)
        {
            if ((ownerForm != null) && (ownerForm.ContainsFocus == true))
            {
                htmlDocument.Focus();

            }
        }
        #endregion

        #region MouseDown
        public void Document_MouseDown(object sender, HtmlElementEventArgs e)
        {
            string href = "";
            mouseDownText = "";
            mouseDownPoint = e.MousePosition;
            HtmlElement clickedElement = ((HtmlDocument)sender).GetElementFromPoint(e.MousePosition);
            HtmlUtil.GetClickTagInfo(clickedElement, ref href, ref mouseDownText);
        }
        #endregion

        #region MouseUp
        public void Document_MouseUp(object sender, HtmlElementEventArgs e)
        {
            if (CheckConsistency() == false)
                return;

            string selectText = "";
            HtmlElement clickedElement = ((HtmlDocument)sender).GetElementFromPoint(e.MousePosition);
            /*<a>内のアドレス*/
            string href = "";
            /*<a>と</a>の間のテキスト*/
            string text = "";

            //<a>タグから情報を取り出す
            HtmlUtil.GetClickTagInfo(clickedElement, ref href, ref text);
            HtmlUtil.GetSelectText(ref selectText, this);

            /* 右クリックがされた */
            if (0 == e.MouseButtonsPressed.CompareTo(MouseButtons.Right))
            {
                /*選択されたテキストがある場合*/
                if ((selectText != null) && (selectText.Length > 0))
                {
                    ContextMenuControls.browserTextMenu.textMenuEvent.Show(this, e.MousePosition,selectText);
                    return;
                }
                /* ttpで始まるアドレスに'h'を補完する */
                if ((0 == text.IndexOf("ttp://", 0)) || (text.StartsWith("ttps://") == true))
                {
                    text = 'h' + text;
                }
                /* アドレスがhttp:// で始まる場合*/
                if ((text.IndexOf("http://") == 0)||(text.StartsWith("https://") == true) || (text.StartsWith("ftp://") == true))
                {
                    ContextMenuControls.browserAddressMenu.addressEvent.Show(this, e.MousePosition, text);
                    return;
                }
                /* ">>"で始まる時 */
                else if (text.IndexOf(">>") == 0)
                {
                    if (this.Name.Equals("ThreadList") == true)
                    {
                        if (0 == href.IndexOf("javascript:void(0);#res", 0))
                        {
                            ContextMenuControls.browserNumberMenu.numberMenuEvent.Show(this, e.MousePosition, text);
                            return;
                        }
                    }
                }
                //ここを解析窓では使わないようにする
                else if ((text.Length == 0) && (href.Length == 0))// && (this.nonTextMenuOn == true))
                {
                    if (this.Name.Equals("ThreadList")==true)
                        ContextMenuControls.browserNonTextMenu.nonTextMenuEvent.Show(this, e.MousePosition);
                }
            }
            /* 左クリックがされた */
            else if (0 == e.MouseButtonsPressed.CompareTo(MouseButtons.Left))
            {
                //ボタン押下時にリンクではない場合
                if ((mouseDownText == null) || (mouseDownText.Length == 0))
                {
                    return;
                }
                //ttpで始まるアドレスに'h'を補完する
                if ((0 == text.IndexOf("ttp://", 0)) || (text.StartsWith("ttps://") == true))
                {
                    text = 'h' + text;
                }
                //アドレスがhttp:// で始まる場合にブラウザで開く*/
                if ((text.IndexOf("http://") == 0) || (text.StartsWith("https://") == true) || (text.StartsWith("ftp://") == true))
                {
                    try
                    {
                        if ((Util.BoardType(text) == Util.TYPE_2CH) ||
                            (Util.BoardType(text) == Util.TYPE_2CHSC) ||
                            (Util.BoardType(text) == Util.TYPE_BLOGBAN) ||
                            (Util.BoardType(text) == Util.TYPE_JBBS) ||
                            (Util.BoardType(text) == Util.TYPE_JIKKYO) ||
                            (Util.BoardType(text) == Util.TYPE_MACHIBBS) ||
                            (Util.BoardType(text) == Util.TYPE_NEXT2CH) ||
                            (Util.BoardType(text) == Util.TYPE_OPEN2CH) ||
                            (Util.BoardType(text) == Util.TYPE_SHIZU) ||
                            (Util.BoardType(text) == Util.TYPE_VIP2CH))
                        {
                            string datUrl = Util.ThreadUrlToDatUrl(text);
                            if (datUrl.Length == 0)
                                return;
                            MainFormConst.threadListTabMain.ShowThread(datUrl, datUrl);
                            return;
                        }
                    }
                    catch { ;}
                    //２ｃｈの場合はブラウザコントロールに任せる
                    if (this.type.Equals("2ch") == true)
                        return;

                    type = HtmlUtil.GetUrlType(text);
                    if (type.Equals("image") == true)
                    {
                        if (Const.opt.browserOption.ImageBrowser.Equals("file") == true)
                            System.Diagnostics.Process.Start(Const.opt.browserOption.ImageBrowserFile, text);
                        if (Const.opt.browserOption.ImageBrowser.Equals("usually") == true)
                            System.Diagnostics.Process.Start(text);
                        if (Const.opt.browserOption.ImageBrowser.Equals("notopen") == true)
                            ;
                    }
                    else if (type.Equals("link") == true)
                    {
                        if (Const.opt.browserOption.LinkBrowser.Equals("file") == true)
                            System.Diagnostics.Process.Start(Const.opt.browserOption.LinkBrowserFile, text);
                        if (Const.opt.browserOption.LinkBrowser.Equals("usually") == true)
                            System.Diagnostics.Process.Start(text);
                        if (Const.opt.browserOption.LinkBrowser.Equals("notopen") == true)
                            ;
                    }
                    
                    return;
                }
                //">>"で始まる時はページ内移動 */
                /*else if (text.IndexOf(">>") == 0)
                {
                    HtmlUtil.MoveToResNum((HtmlDocument)sender, text);
                    return;
                }*/
                else if (0 == href.IndexOf("javascript:void(0);#ANARYNUM", 0))
                {
                    string[] item = href.Split('#');
                    string num = item[2];
                    string datUrl = item[3];

                    MainFormConst.PopUpWindow(Cursor.Position, threadView, datUrl, num);//, "idFromID");
                }

                else if (0 == href.IndexOf("javascript:void(0);#WORD#", 0))
                {
                    string data = href.Substring(25, href.Length - 25);
                    MainFormConst.PopUpWindow(Cursor.Position, threadView, threadView.datUrl, data, "WORD");
                    return;
                }

                else if ((text.IndexOf("2BP") == 0) ||
                    (text.IndexOf("BRZ") == 0) ||
                    (text.IndexOf("PLT") == 0) ||
                    (text.IndexOf("DIA") == 0) ||
                    (text.IndexOf("S★") == 0))
                {
                    if (0 == href.IndexOf("javascript:void(0);#BE:", 0))
                    {
                        string be = href.Split('#')[1].Remove(0, 3);
                        string datUrl = href.Remove(0, 23 + be.Length + 1);
                        string beUrl = "";

                        if (Util.BoardUrlToBoardTypeName(datUrl).Equals("2ch") == true)
                        {
                            beUrl = "http://be.2ch.net/user/" + be;
                            System.Diagnostics.Process.Start(beUrl);
                        }
                        else if (Util.BoardUrlToBoardTypeName(datUrl).Equals("2chsc") == true)
                        {
                            beUrl = "http://be.2ch.sc/test/p.php?i=" + be;
                            System.Diagnostics.Process.Start(beUrl);
                        }
                        else
                            ;
                    }
                }
            }
            /* それ以外がクリックされた */
            else
            {
                return;
            }
            /* レス番号をクリックした場合 */
            if (0 == href.IndexOf("javascript:void(0);#num", 0))
            {
                text = ">>" + text;
                ContextMenuControls.browserNumberMenu.numberMenuEvent.Show(this, e.MousePosition, text);
                return;
            }
        }
        #endregion
    }
}