using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using Gecko;
using Microsoft.VisualBasic;
//using MyScript;
//using Irony.Interpreter;
//using Irony.Interpreter.Ast;
//using Irony.Parsing;
using System.Threading;
using System.Diagnostics;
//using ScriptTest;
using myBuiltInMethod;
using WeifenLuo.WinFormsUI.Docking;



namespace geckoFXbrowser
{


    public partial class Form_main : Form
    {

        public GeckoWebBrowser activeBrowser = null;
        public myBuiltInMethod.FormScriptInterfaces formlib = null;
        private const char delim = '\t';
        public string EXEPath { get; set; }
        private FileMan fileman;

        public delegate void AfterDocCompHandler(object sender, EventArgs e);


        public Form_main()
        {

            EXEPath = System.Reflection.Assembly.GetEntryAssembly().Location;
            //Application.ExecutablePath;
            Xpcom.Initialize(@"C:\xulrunner\12\xulrunner");
            Application.ApplicationExit += (sender, e) =>
            {
                Xpcom.Shutdown();
            };


            init();
            newDoc();
        }

        public void init()
        {
            //Xpcom.Initialize(@"C:\xulrunner\12\xulrunner");
            InitializeComponent();
            loadSettings(EXEPath);

            formlib = new FormScriptInterfaces();
            foreach (var item in menuitemList)
            {
                formlib.Add(item.Key.ToString() , item.Value);
            }


            //////formlib.Add(this.MenuItem_clickXpath);
            //////formlib.Add(this.MenuItem_changeID);
            //////formlib.Add(this.MenuItem_favorites);

        }





        private void MenuItem_AddThispage_Click(object sender, EventArgs e)
        {
            if(activeBrowser == null || activeBrowser.Document == null)
            {
                return;
            }
            string defaultstr = activeBrowser.DocumentTitle;

            try
            {
                //タイトル以外に指標になるものがあるならば、XPATHなどで抜き出しても良い。
                //GeckoElement[] title = activeBrowser.Document.GetElements("/html/body/div/div[2]/center/font").ToArray<GeckoElement>();
                //if (title.Length > 0)
                //{
                //    defaultstr = title[0].TextContent;
                //}
            }
            catch (Exception ex)
            {
                MessageBox.Show("えらー " + ex.Message);
            }

            var str = Microsoft.VisualBasic.Interaction
                        .InputBox("タイトルを入力してください", "タイトル入力", defaultstr);

            var item = new ToolStripMenuItem(str);
            item.Tag = activeBrowser.Url.ToString();
            this.MenuItem_favorites.DropDownItems.Add(item);

            //追加されたアイテムのクリックイベント処理
            item.Click += new EventHandler( MenuItem_navi_Click );
        }

        private void お気に入り編集ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var win = new EditFavorite.EditableWindow(this.MenuItem_favorites, MenuItem_navi_Click);
            win.showWindow("お気に入り編集", new string[] { "編集", "このページを追加" });
        }

        //ナビゲート系は一緒の処理
        private void MenuItem_navi_Click(object sender, EventArgs e)
        {
            if(((ToolStripMenuItem)sender).Tag == null)
                return;

            if(activeBrowser == null)
                newDoc();
            activeBrowser.Navigate(((ToolStripMenuItem)sender).Tag.ToString());
        }





        private ToolStripMenuItem findFavorite(string MenuName)
        {
            return findMenuItem("お気に入り", MenuName);
        }

        private ToolStripMenuItem findMenuItem(string rootmenu, string MenuName)
        {
            ToolStripMenuItem ret = null;

            foreach (var item in this.menuitemList.Keys)
            {
                if (item.Contains(rootmenu) && item.Contains(MenuName))
                {
                    ret = menuitemList[item];
                    break;
                }
            }
            return ret;
        }





        private void newTABToolStripMenuItem_Click(object sender, EventArgs e)
        {
            newDoc();
        }

        private browserDoc newDoc()
        {
            browserDoc doc = new browserDoc();
            doc.Text = "new document"; 
            doc.Show(dockPanel1);
            doc.OnStatusChange += statusLabelUpdate;
            doc.OnHistoryNewEntry += HistoryUpdate;
            
            //scriptに公開する
            formlib.Add(doc.Name, doc);
            return doc;
            
            
        }

        private void dockPanel1_ActiveContentChanged(object sender, EventArgs e)
        {
            activeBrowser = getActiveBrowser();
            if(activeBrowser != null)
            {
                this.toolStripStatusLabel1.Text = activeBrowser.StatusText;
                activeBrowser.Refresh();
            }
        }

        private GeckoWebBrowser getActiveBrowser()
        {
            if(dockPanel1.ActiveContent != null)
                return ((browserDoc)this.dockPanel1.ActiveDocument).browser;
            else
                return null;
        }


        private void statusLabelUpdate(browserDoc sender, object status)
        {
            if(sender.IsActivated)
                this.toolStripStatusLabel1.Text = (string)status;
        }

        private void HistoryUpdate(browserDoc sender, object newentry)
        {
            System.Diagnostics.Debug.WriteLine("new " + newentry.ToString());
            
            if(sender.IsActivated)
            {
                if(sender.browser == null) return;
                if(sender.browser.Url.ToString() == "") return;

                var title = sender.browser.DocumentTitle;
                var item = new ToolStripMenuItem(title);
                item.Tag = newentry.ToString();
                item.Click += (s, e) =>
                {
                    if(activeBrowser == null)
                    {
                        newDoc();
                    }

                    this.activeBrowser.Navigate(((ToolStripMenuItem)s).Tag.ToString());

                };
                historyToolStripMenuItem.DropDownItems.Add(item);
                
            }
        }

        //window close
        private void Form_main_FormClosing(object sender, FormClosingEventArgs e)
        {
            //foreach(var w in this.dockPanel1.DockWindows)
            //{
            //    w.Dispose();
            //}

            saveMenuInfo(this.MenuItem_favorites, fileman.FilePath_Favorites, new string[] { "編集", "このページを追加" });

        }

        private browserDoc lastbrowserDoc;
        private void dockPanel1_Leave(object sender, EventArgs e)
        {
            lastbrowserDoc = (browserDoc)dockPanel1.ActiveDocument;
        }






    }
}
