/*# Copyright (c) 2008 Hideki Ikemoto
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.*/

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

using nispi.Menu;

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
    {
        public MyWebBrowser control = new MyWebBrowser();

        public static MainForm form = null;

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

        public BrowserParts()
        {
            control.Anchor = (AnchorStyles)
                ((AnchorStyles.Top)
                | (AnchorStyles.Bottom)
                | (AnchorStyles.Left)
                | (AnchorStyles.Right));
            control.Location = new Point(1, 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;

            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);
        }

        public bool CheckConsistency()
        {
            try
            {
                int index = Const.form.threadListTabControlParts.control.Controls.Count;
                this.threadView = ViewMediator.threadListTabMain.viewList[index];
                return true;
            }
            catch
            {
                return false;
            }
        }

        //サイズ//ラッピング
        public Size Size
        {
            set
            {
                this.control.Size = value;
            }
            get
            {
                return this.control.Size;
            }
        }
        //ドキュメント
        public HtmlDocument Document
        {
            /*set
            {
                this.control.Document = value;
            }*/
            get
            {
                return this.control.Document;
            }
        }
        public bool AllowNavigation
        {
            set
            {
                this.control.AllowNavigation = value;
            }
            get
            {
                return this.control.AllowNavigation;
            }
        }
        public void BrowserClear()
        {
            try
            {
                if (control.Document != null)
                {
                    control.Document.OpenNew(true);
                }
                else
                {
                    control.Navigate("about:blank");
                }
            }
            catch { ;}
        }
        //ドキュメントを開く
        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;
            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"))
            {
                System.Diagnostics.Debug.WriteLine("focus1");
                GetFocus(htmlDocument);
            }
            else
            {
                System.Diagnostics.Debug.WriteLine("focus2");
                if (htmlDocument.Focused == false)
                {
                    System.Diagnostics.Debug.WriteLine("focus3");
                    //ポップアップウィンドウがある場合は無条件で消す
                    if (ViewMediator.htmlPopUpWindowWidget.popUpList.Count > 0)
                    {
                        System.Diagnostics.Debug.WriteLine("focus");
                        /* レス番号 */
                        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))
                            {
                                ViewMediator.htmlPopUpWindowWidget.RemoveAllPopUp();
                                GetFocus(htmlDocument);
                            }
                        }
                        else if (href.Length == 0)
                        {
                            ViewMediator.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);

                        if (true == PopUpManager.openNum.Equals(number))
                        {
                        }
                        else
                        {
                            PopUpManager.openDatUrl = datUrl;
                            PopUpManager.openNum = number;
                            PopUpManager.openFlag = true;
                            PopUpManager.lastTime = System.Environment.TickCount & int.MaxValue;
                            System.Diagnostics.Debug.WriteLine("new:" + number);

                            ViewMediator.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);

                        System.Diagnostics.Debug.WriteLine("new:" + id);
                        if (true == PopUpManager.openNum.Equals(id))
                        {
                        }
                        else
                        {
                            PopUpManager.openNum = id;
                            ViewMediator.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];

                        System.Diagnostics.Debug.WriteLine("new:" + number);

                        if (true == PopUpManager.openNum.Equals(number))
                        {
                        }
                        else
                        {
                            PopUpManager.openNum = number;
                            ViewMediator.PopUpWindow(Cursor.Position, threadView, datUrl, number, "POPNUM");
                        }
                    }
                }
            }
            else
            {
                PopUpManager.openNum = "0";
            }
        }
        public void GetFocus(HtmlDocument htmlDocument)
        {
            //フォームが一番上である場合。
            if (MapPopUpForm.popUp.Visible == true)
            {
                if (MapPopUpForm.popUp.ContainsFocus == true)
                    htmlDocument.Focus(); ;
            }
            else if (form.ContainsFocus == true)
            {
                System.Diagnostics.Debug.WriteLine("focus");
                //ViewMediator.htmlPopUpWindowWidget.RemoveAllPopUp();
                htmlDocument.Focus();

            }
        }
        #endregion

        #region MouseDown
        public void Document_MouseDown(object sender, HtmlElementEventArgs e)
        {
            string href = "";
            mouseDownText = "";
            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.control);

            /* 右クリックがされた */
            if (0 == e.MouseButtonsPressed.CompareTo(MouseButtons.Right))
            {
                /*選択されたテキストがある場合*/
                if ((selectText != null) && (selectText.Length > 0))
                {
                    textMenu.OpenTextMenu(control, e.MousePosition, selectText);
                    return;
                }
                /* ttpで始まるアドレスに'h'を補完する */
                if (0 == text.IndexOf("ttp://", 0))
                {
                    text = 'h' + text;
                }
                /* アドレスがhttp:// で始まる場合*/
                if (text.IndexOf("http://") == 0)
                {
                    addressMenu.OpenAddressMenu(control, e.MousePosition, text);
                    return;
                }
                /* ">>"で始まる時 */
                else if (text.IndexOf(">>") == 0)
                {
                    /* レス番号をクリックした場合 */
                    if (0 == href.IndexOf("javascript:void(0);#res", 0))
                    {
                        numberMenu.OpenNumberMenu(control, e.MousePosition, text);
                        return;
                    }
                }
                //ここを解析窓では使わないようにする
                else if ((text.Length == 0) && (href.Length == 0))
                {
                    nonTextMenu.OpenNonTextMenu(control, 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 = 'h' + text;
                }
                //アドレスがhttp:// で始まる場合にブラウザで開く*/
                if (text.IndexOf("http://") == 0)
                {
                    System.Diagnostics.Process.Start(text);
                    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];

                    ViewMediator.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);
                    ViewMediator.PopUpWindow(Cursor.Position, threadView, threadView.datUrl, data, "WORD");
                    return;
                }
            }
            /* それ以外がクリックされた */
            else
            {
                return;
            }
            /* レス番号をクリックした場合 */
            if (0 == href.IndexOf("javascript:void(0);#num", 0))
            {
                text = ">>" + text;
                numberMenu.OpenNumberMenu(control, e.MousePosition, text);
                return;
            }
        }
        #endregion
    }
}