using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using System.Reflection;
using System.Drawing;
using System.IO;
using System.Drawing.Imaging;
using System.Security.Permissions;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;

namespace US.Browser.IE
{
    /// <summary>
    /// webbrower统一使用接口区域
    /// </summary>
    [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
    [System.Runtime.InteropServices.ComVisibleAttribute(true)]

    public class BrowserDAO
    {
        public WebBrowser _UWB;//头部操作的WebBrowser
        public List<WebBrowser> _UBL = new List<WebBrowser>();//所有的WebBrowser
        public USMain _UF;//使用域的控件区域
        public FVCBrower _UFV; public RespondWeb _UVB;
        public Respond_setting RS;
        public Popup Popup;

        #region 创建头部窗体

        /// <summary>
        /// 带参数构造
        /// </summary>  
        /// <param name="UWB"></param>
        /// <param name="UF"></param>
        public BrowserDAO(WebBrowser UWB, USMain UF)
        {
            _UF = UF; _UWB = UWB;
            this._UFV = new FVCBrower(this);//初始化收藏夹
            this._UVB = new RespondWeb(this, _UFV);//功能设置
            this.RS = new Respond_setting();//设置区域
        }

        /// <summary>
        /// 新建一个页面
        /// </summary>
        /// <param name="UURL"></param>
        /// <param name="UN"></param>
        public WebBrowser AddBrowser(string UURL, string UN)
        {
            Rectangle USZ = _UF.ClientRectangle; bool ty = _UWB.Location.Y != -35, ws = _UF.WindowState != FormWindowState.Maximized;
            Size SZ = ty ? ws ? new Size(USZ.Width - 6, USZ.Height - _UWB.Height - 6) : new Size(USZ.Width, USZ.Height - _UWB.Height) : new Size(USZ.Width, USZ.Height - 2);
            Point PT = ty ? ws ? new Point(3, _UWB.Height + 3) : PT = new Point(0, _UWB.Height) : new Point(0, 2);
            WebBrowser _t = new BrowserListener(UN, PT, SZ, UURL, this)._UWB; _UF.Controls.Add(_t); _UBL.Add(_t); return _t;//设置窗口 //添加窗口
        }

        #endregion

        #region 头部功能区域


        /// <summary>
        /// 关闭一个页面
        /// </summary>
        /// <param name="name"></param>
        public void CloseOneBrowser(string UN)
        {
            BLL.USIE.setTimeout(1, delegate(System.Timers.ElapsedEventArgs e)
            {
                try
                {
                    int i; WebBrowser _UWB;
                    for (i = 0; i < _UBL.Count; i++)
                    {
                        _UWB = _UBL[i];
                        if (_UWB.Name == UN) { _UBL.Remove(_UWB); _UWB.Dispose(); break; }
                    }
                    BLL.WindowHWND.freem();
                }
                catch (Exception ex) { }
            });
            return;
        }

        /// <summary>
        /// 关闭全部页面
        /// </summary>
        public void CloseAllBrowser()
        {
            int i; WebBrowser _UWB;
            for (i = 0; i < _UBL.Count; i++)
            {
                _UWB = _UBL[i]; _UWB.Dispose(); _UBL.Remove(_UWB);
            }
            BLL.WindowHWND.freem();
        }

        /// <summary>
        /// 获取指定的webbrower
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public WebBrowser FindBrowser(string UN)
        {
            int i; WebBrowser _UWB = null;
            for (i = 0; i < _UBL.Count; i++)
            {
                _UWB = _UBL[i];
                if (_UWB.Name == UN) { break; }
                _UWB = null;
            }
            return _UWB;
        }

        /// <summary>
        /// 根据Url获取webbrower
        /// </summary>
        /// <param name="UN"></param>
        /// <returns></returns>
        public WebBrowser FindWebUrl(string UN)
        {
            for (int i = 0; i < _UBL.Count; i++) { if (_UBL[i].Url.AbsoluteUri.IndexOf("http://www.1473.cn") > -1) { return _UBL[i]; } }
            return null;
        }

        /// <summary>
        /// 跳转指定的页面
        /// </summary>
        /// <param name="name"></param>
        /// <param name="url"></param>
        public void ModifyOneBrowser(string UN, string UURL)
        {
            WebBrowser _UWB = this.FindBrowser(UN); BLL.WindowHWND.freem();
            if (_UWB != null) { if (_UWB.Document == null) { CloseOneBrowser(UN); return; } _UWB.Url = new Uri(UURL); }// _UWB.Navigate(UURL);
        }

        /// <summary>
        /// 获取加载页面信息信息
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public string BrowserToJson(WebBrowser _UWB, bool UE)
        {
            int i; string _UST = "", _UY = _UWB.Url.Scheme + "://" + _UWB.Url.Host; HtmlElementCollection UDE = _UWB.Document.GetElementsByTagName("link");
            if (UE == false)//需要获取ico
            {
                for (i = 0; i < UDE.Count; i++) { if (UDE[i].GetAttribute("rel").ToLower() == "shortcut icon") { _UST = UDE[i].GetAttribute("href").ToString(); break; } } new Uri(_UST, UriKind.RelativeOrAbsolute);
                if (_UST == "") { _UST = _UWB.Url.Scheme + "://" + _UWB.Url.Host + (_UST == "" ? "/favicon.ico" : _UST); } else { _UST = new Uri(new Uri(_UY), _UST).ToString(); }
                MemoryStream _UMS = GetUrlImg(_UST, ImageFormat.Png); _UST = _UMS == null ? "" : "data:image/jpeg;base64," + Convert.ToBase64String(_UMS.GetBuffer()); if (_UMS != null) { _UMS.Close(); _UMS.Dispose(); }
            }
            List<string[]> _T = new List<string[]> { new string[] { "Name", _UWB.Name }, new string[] { "Shortcut_Icon", _UST }, new string[] { "Url", _UWB.Url == null ? "" : _UWB.Url.ToString() }, new string[] { "Visible", _UWB.Visible.ToString() }, new string[] { "Title", (_UWB.DocumentTitle == "" && _UWB.StatusText != "完成") ? _UWB.StatusText.ToString() : _UWB.DocumentTitle }, new string[] { "CanPrevious", _UWB.CanGoBack.ToString() }, new string[] { "CanNext", _UWB.CanGoForward.ToString() } };
            Utitiy.StringJoiner _S = new Utitiy.StringJoiner(); _S = "{"; for (i = 0; i < _T.Count; i++) { _S += "'"; _S += _T[i][0]; _S += "':'"; _S += _T[i][1]; if (i != _T.Count - 1) { _S += "',"; } } _S += "'}"; return _S;
        }

        /// <summary>
        /// ico转化成png
        /// </summary>
        /// <returns></returns>
        public static MemoryStream GetUrlImg(string img, ImageFormat tp)
        {
            try
            {
                System.Net.HttpWebRequest webrq = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(new Uri(img));
                webrq.Timeout = 5000; webrq.ServicePoint.Expect100Continue = false;
                System.Net.HttpWebResponse webres = (System.Net.HttpWebResponse)webrq.GetResponse(); Bitmap imt;
                if (webres.StatusCode == System.Net.HttpStatusCode.OK && webres.ContentLength > 0)
                {
                    using (Stream stream = webres.GetResponseStream())
                    {
                        Image image = Image.FromStream(stream);
                        using (imt = new Bitmap(16, 16))
                        {
                            Graphics g = Graphics.FromImage(imt); g.Clear(System.Drawing.Color.Transparent);
                            g.DrawImage(image, new System.Drawing.Rectangle(0, 0, 16, 16), new System.Drawing.Rectangle(0, 0, 16, 16), System.Drawing.GraphicsUnit.Pixel);
                            MemoryStream ms = new MemoryStream(); imt.Save(ms, tp); imt.Dispose(); image.Dispose(); g.Dispose(); return ms;
                        }
                    }
                }
                webrq.Abort(); webres.Close();
            }
            catch (Exception e) { }//输出的页面信息
            return null;
        }

        /// <summary>
        /// 设置显示的webbower变化
        /// </summary>
        public void ChangeBrowsersSize()
        {
            int i; WebBrowser _UWB;
            for (i = 0; i < _UBL.Count; i++)
            {
                _UWB = _UBL[i]; _UWB.Location = new Point(2, this._UWB.Height); _UWB.Width = this._UF.ClientRectangle.Width - 4; _UWB.Height = this._UF.ClientRectangle.Height - this._UWB.Height - 2;
            }
        }

        private FormWindowState _st;
        private bool F11TF = false;

        /// <summary>
        /// 统一F11
        /// </summary>
        /// <param name="TF"></param>
        /// <param name="TopWB"></param>
        public void TYUWBF11(WebBrowser TopWB)
        {
            F11TF = !F11TF;
            if (F11TF)//全屏
            {
                _st = _UF.WindowState; _UF.WindowState = FormWindowState.Maximized;//设置全屏
                _UVB.BSSZ(new Point(0, 2), new Point(0, -35), new Size(_UF.Width, _UF.Height - 2), new Size(_UF.Width, TopWB.Height));//大小设置
            }
            else { _UF.WindowState = _st; _UVB.DXBH(_st == FormWindowState.Maximized); }
        }

        #endregion

        #region 无用函数区域

        ///// <summary>
        ///// 自定义计时器
        ///// </summary>
        ///// <param name="interval"></param>
        ///// <param name="action"></param>
        //public void SetTimeout()
        //{
        //    System.Timers.Timer _TM = new System.Timers.Timer();
        //    int i = 0;//计时器变量
        //    _TM.Elapsed += new System.Timers.ElapsedEventHandler(delegate(object sender, System.Timers.ElapsedEventArgs e)
        //    {
        //        i++;
        //        /* if (_TM.AutoReset == false && i % 1 == 0) { Popup.UTC(); _TM.AutoReset = true; _TM.Interval = 1000; }
        //         else if (i % 1800 == 0 && Popup.Visible == false) { Popup.UTC(); }
        //         else if (i % 300 == 0) { Popup.REUTC(); }*/
        //    });
        //    //计时器执行时间区 _TM.Enabled = false;  /*设置执行函数 例如: a() */
        //    _TM.Interval = 5000;//时间间隔
        //    _TM.Start();//启动事件
        //    //_TM.Enabled = true;//添加这个事件设置计时器是否可用
        //    _TM.AutoReset = false;

        //}

        #endregion
    }

}