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

            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
            }



            try {

                string[] blockedUrls = { "https://www.youtube.com/watch?v=dQw4w9WgXcQ", "https://www.youtube.com/watch?v=xm3YgoEiEDc", "https://www.youtube.com/watch?v=xvFZjo5PgG0", "https://www.youtube.com/watch?v=O91DT1pR1ew", "https://www.youtube.com/watch?v=o-YBDTqX_ZU", "https://www.youtube.com/watch?v=H8ZH_mkfPUY", "https://www.youtube.com/watch?v=o-YBDTqX_ZU", "https://www.youtube.com/watch?v=xvFZjo5PgG0" };
                string[] blockedDrms = { "https://www.netflix.com/", "http://www.netflix.com/", "https://netflix.com/", "http://netflix.com/", "https://www.disneyplus.com/", "http://www.disneyplus.com/", "https://disneyplus.com/", "http://disneyplus.com/", "https://www.twitch.tv/", "http://www.twitch.tv/", "https://twitch.tv/", "http://twitch.tv/", "https://www.tiktok.com/", "http://www.tiktok.com/", "https://tiktok.com/", "http://tiktok.com/" };
                string[] incompatibleExtSites = { "https://www.chrome.google.com", "https://chrome.google.com", "https://www.addons.mozilla.org", "https://addons.mozilla.org" };

                string currentAddress = chromiumWebBrowser1.Address;

                if (!_isBlocked)
                {
                    foreach (string blockedDrm in blockedDrms)
                    {
                        if (currentAddress.StartsWith(blockedDrm))
                        {
                            chromiumWebBrowser1.Stop(); // cancel the navigation
                            _isBlocked = true;
                            chromiumWebBrowser1.LoadHtml("<html> <head> </head> <style> body{ background-color: rgb(214, 214, 214); } .center{ text-align: center; } .text{ margin-top: 20%; font-family: Arial; } div{ background-color: #f5f5f5; border-radius: 15px; width: 500px; margin-left: 35%; padding: 10px; } </style> <body class=\"center\"> <div class=\"text\"> <h1>Error!</h1> <h3 id=\"domain\"></h3> </div> </body> <script> document.getElementById(\"domain\").innerHTML = window.location.hostname + (' requires a DRM (Digital Rights Management) which Xero Browser does not support!'); </script></html>", blockedDrm);
                            break;
                        }
                    }

                    foreach (string blockedUrl in blockedUrls)
                    {
                        if (currentAddress.StartsWith(blockedUrl))
                        {
                            chromiumWebBrowser1.Stop(); // cancel the navigation
                            _isBlocked = true;
                            chromiumWebBrowser1.LoadHtml("<html> <head> </head> <style> body{ background-color: rgb(214, 214, 214); } .center{ text-align: center; } .text{ margin-top: 20%; font-family: Arial; } div{ background-color: #f5f5f5; border-radius: 15px; width: 500px; margin-left: 35%; padding: 10px; } </style> <body class=\"center\"> <div class=\"text\"> <h1>Rickroll Blocked!</h1> <h3>Being rickrolled is disabled.</h3> </div> </body></html>", blockedUrl);
                            break;
                        }
                    }

                    foreach (string incompatibleExtSite in incompatibleExtSites)
                    {
                        if (currentAddress.StartsWith(incompatibleExtSite))
                        {
                            chromiumWebBrowser1.Stop(); // cancel the navigation
                            _isBlocked = true;
                            chromiumWebBrowser1.LoadHtml("<html> <head> </head> <style> body{ background-color: rgb(214, 214, 214); } .center{ text-align: center; } .text{ margin-top: 20%; font-family: Arial; } div{ background-color: #f5f5f5; border-radius: 15px; width: 500px; margin-left: 35%; padding: 10px; } </style> <body class=\"center\"> <div class=\"text\"> <h1>Error!</h1> <h3>Xero Browser has no extension support (Yet).</h3> </div> </body></html>", incompatibleExtSite);
                            break;
                        }
                    }
                }

            }
            catch (System.Net.WebException) { }
            catch (System.ArgumentException) { }
        }

        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.google.com/search?q=" + txtSearchOrUrl.Text.Trim().Replace(" ", "+") + "&sourceid=chrome&ie=UTF-8");
                }
            }
        }

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

}