using System;
using System.ComponentModel;
using System.IO;
using System.Windows.Forms;
using Bunifu.Utils;
using CefSharp;
using CefSharp.WinForms;
using EasyTabs;
using Google.Apis.Safebrowsing.v4;
using Google.Apis.Safebrowsing.v4.Data;
using Google.Apis.Services;
using System.Collections.Generic;
using System.Threading.Tasks;
using XeroBrowser.Properties;
using static System.Net.WebRequestMethods;
using System.Linq;
// ReSharper disable PossibleNullReferenceException

namespace XeroBrowser
{
    public partial class FrmBrowser : Form
    {   
        Uri _fileUri;
        Uri _fileUri2;
        Uri _safebrowsingblockpage;
        public FrmBrowser()
        {
            InitializeComponent();
            chromiumWebBrowser1.DownloadHandler = new DownloadHandler(this);
            chromiumWebBrowser1.LifeSpanHandler = new LifeSpanHandler();
            chromiumWebBrowser1.MenuHandler = new MenuHandler();
            chromiumWebBrowser1.DisplayHandler = new DisplayHandler(this);
            chromiumWebBrowser1.RequestHandler = new RequestHandler();

            string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "index.html");
            _fileUri = new Uri(filePath);
            string fileUrl = _fileUri.AbsoluteUri;

            string filePath2 = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "loaderror.html");
            _fileUri2 = new Uri(filePath2);
            string fileUrl2 = _fileUri2.AbsoluteUri;

            string safebrowsingblockpath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "safebrowsingblock.html");
            _safebrowsingblockpage = new Uri(safebrowsingblockpath);
            string safebrowsingblockpage = _safebrowsingblockpage.AbsoluteUri;

            chromiumWebBrowser1.Load(fileUrl);
            txtSearchOrUrl.Text = "";
            txtSearchOrUrl.IconRight = null;
            CheckForIllegalCrossThreadCalls = false;
        }


        public TitleBarTabs ParentTabs => (ParentForm as TitleBarTabs);

        private void btnForward_Click(object sender, EventArgs e)
        {
            if (chromiumWebBrowser1.CanGoForward) chromiumWebBrowser1.Forward();
            
        }

        public void ChangeUrl(string url)
        {
            chromiumWebBrowser1.Load(url);
        }

        private void btnBack_Click(object sender, EventArgs e)
        {
            if (chromiumWebBrowser1.CanGoBack) chromiumWebBrowser1.Back();

        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            chromiumWebBrowser1.Reload();
        }

        private bool _isBlocked;
        private void chromiumWebBrowser1_LoadingStateChanged(object sender, LoadingStateChangedEventArgs e)
        {
            chromiumWebBrowser1.LoadingStateChanged += async (s, args) =>
             {
                /* if (args.IsLoading)
                {
                     var isUnsafe = await Program.IsUrlUnsafe(args.Browser.MainFrame.Url, "AIzaSyCQV-s52iNah-il6T5iFuqo6M_JzcLyaxs");
                    if (isUnsafe)
                    {
                        chromiumWebBrowser1.Stop(); // cancel the navigation
                        _isBlocked = true;
                        string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "safebrowsingblock.html");
                        _safebrowsingblockpage = new Uri(filePath);
                        string fileUrl = _safebrowsingblockpage.AbsoluteUri;
                        chromiumWebBrowser1.Load(fileUrl); ;
                        
                    }
                }
                */
          };

            if (e.IsLoading)
            {
                loadingIndicator.Visible = true;
                btnRefresh.Visible = false;
            }
            else
            {
                loadingIndicator.Visible = false;
                btnRefresh.Visible = true;
            }

            try
            {
                Invoke((Action)delegate
                {
                    if (txtSearchOrUrl != null && chromiumWebBrowser1 != null)
                    {
                        txtSearchOrUrl.Text = !chromiumWebBrowser1.Address.EndsWith(_fileUri.ToString()) && !chromiumWebBrowser1.Address.EndsWith(_fileUri2.ToString()) ? chromiumWebBrowser1.Address : "";
                    }
                });

            }
            catch (ObjectDisposedException) { }
            catch (InvalidAsynchronousStateException) { }

            bool isMessageBoxShown = false;

            var uri = new Uri(chromiumWebBrowser1.Address);
            if (uri.Scheme == "file")
            {
                txtSearchOrUrl.IconLeft = Resources.local;
                txtSearchOrUrl.IconRight = Resources.bookmarks_unbookmarked;

            }
            else if (uri.Scheme == "https")
            {
                txtSearchOrUrl.IconLeft = Resources.secure;
                txtSearchOrUrl.IconRight = Resources.bookmarks_unbookmarked;
            }
            else if (uri.Scheme == "http")
            {
                txtSearchOrUrl.IconLeft = Resources.insecure1;
                txtSearchOrUrl.IconRight = Resources.bookmarks_unbookmarked;
                if (!_isBlocked && !isMessageBoxShown) // Check if the scheme is HTTP, the message box hasn't been shown, and it's not blocked
                {
                    isMessageBoxShown = true; // Update the variable to indicate that the message box has been shown
                    MessageBox.Show(@"Warning: This site is insecure! Your personal information may be at risk, or hackers can install malicious software on your device.", @"Xero Browser", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }

            if (e.IsLoading)
            {
                // Don't return, allow the code to execute the rest of the logic
            }



        }

        private void chromiumWebBrowser1_TitleChanged(object sender, TitleChangedEventArgs e)
        {
            try
            {
                Invoke((Action)delegate { FindForm().Text = e.Title; });
            }
            catch (ObjectDisposedException) { }
        }

        private void btnSettings_Click(object sender, EventArgs e)
        {
            Backdrop.Show(new FrmSettings());
        }

        private void chromiumWebBrowser1_KeyDown(object sender, KeyEventArgs e)
        {
        }

        private void bunifuImageButton1_Click(object sender, EventArgs e)
        {
            chromiumWebBrowser1.ShowDevTools();
            
        }

        private void chromiumWebBrowser1_LoadError(object sender, LoadErrorEventArgs e)
        {
           // string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "loaderror.html");
           // _fileUri2 = new Uri(filePath);
           // string fileUrl = _fileUri2.AbsoluteUri;
           // chromiumWebBrowser1.Load(fileUrl);
        }

        private void txtSearchOrUrl_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter && txtSearchOrUrl.Text.Trim().Length > 0)
            {
                if (txtSearchOrUrl.Text.Contains("."))
                {
                    chromiumWebBrowser1.Load(txtSearchOrUrl.Text.Trim());
                }
                else
                {
                    chromiumWebBrowser1.Load("https://www.duckduckgo.com/?q=" + txtSearchOrUrl.Text.Trim().Replace(" ", "+"));
                }
            }
        }

        private void txtSearchOrUrl_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {

                e.Handled = true;
                e.SuppressKeyPress = true;

            }
        }

        private void bunifuImageButton3_Click(object sender, EventArgs e)
        {

        }

        private void bunifuImageButton2_Click(object sender, EventArgs e)
        {
            chromiumWebBrowser1.Load("https://google.com");
        }
    }

}