using C1.Xaml.RichTextBox;
using System;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using C1.Xaml.RichTextBox.Documents;
using Windows.UI.Popups;
using Windows.UI.Core;
using Windows.UI.Xaml.Media;
using Windows.UI;

namespace ControlExplorer.Controls.RichTextBox
{
    public partial class HyperlinkPopup : UserControl
    {
        private C1RichTextBox _richTextBox;
        private Popup _popup;
        public event EventHandler<object> Closed;

        public HyperlinkPopup(C1RichTextBox rtb)
        {
            InitializeComponent();
            // init C1Popup
            _popup = new Popup();
            _popup.Child = this;

            // set local reference to C1RichTextBox
            _richTextBox = rtb;
            _popup.Closed += _popup_Closed;
        }

        void _popup_Closed(object sender, object e)
        {
            if(Closed != null)
            {
                Closed(null, e);
            }
        }

        public void ShowPopup()
        {
            // set url text
            txtText.Text = _richTextBox.Selection.Text;

            // set url if opening existing hyperlink
            if (_richTextBox.Selection.Html.Contains("<a") && _richTextBox.Selection.Html.Contains("href"))
            {
                // parse out the href part
                int i = _richTextBox.Selection.Html.IndexOf("href");
                string j = _richTextBox.Selection.Html.Substring(i);
                int k = j.IndexOf('"');
                string l = j.Substring(k + 1);

                txtUrl.Text = l.Substring(0, l.IndexOf('"'));
            }
            else
            {
                txtUrl.Text = "http://";
            }

            // open C1Popup
            _popup.IsOpen = true;
        }

        public void ClosePopup()
        {
            // close C1Popup
            _popup.IsOpen = false;

            // set focus back to the richtextbox
            _richTextBox.Focus(FocusState.Programmatic);
        }

        private void btnOK_Click(object sender, RoutedEventArgs e)
        {
            Uri url = null;
            try
            {
                url = new Uri(txtUrl.Text, UriKind.Absolute);
            }
            catch (FormatException)
            {
                if (txtUrl.Text.Trim().Equals("http://", StringComparison.OrdinalIgnoreCase))
                {
                    this.ClosePopup();
                    return;
                }

                try
                {
                    url = new Uri("http://" + txtUrl.Text, UriKind.Absolute);
                }
                catch (FormatException)
                {
                    var messageDialog = new MessageDialog("Invalid url");
                    messageDialog.ShowAsync();
                }
            }

            using (new DocumentHistoryGroup(_richTextBox.DocumentHistory))
            {
                if (_richTextBox.Selection.Text != txtText.Text)
                {
                    _richTextBox.Selection.Delete();
                    var run = new C1Run { Text = txtText.Text };
                    _richTextBox.Selection.Start.InsertInline(run);
                    run.ContentRange.MakeHyperlink(url);
                    _richTextBox.Selection = run.ContentRange;
                }
                else
                {
                    _richTextBox.Selection.MakeHyperlink(url);
                }
            }
            this.ClosePopup();
        }

        private void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            this.ClosePopup();
        }

        private void btnRemove_Click(object sender, RoutedEventArgs e)
        {
            using (new DocumentHistoryGroup(_richTextBox.DocumentHistory))
            {
                var range = _richTextBox.Selection;
                range.TrimRuns();
                _richTextBox.Selection = range;

                foreach (var r in range.EditRanges)
                {
                    r.RemoveHyperlinks();
                }
            }
            this.ClosePopup();
        }

        private void txtUrl_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (txtUrl.Text.Length > 0)
            {
                btnOK.ClearValue(Button.BorderBrushProperty);
                btnOK.ClearValue(Button.BackgroundProperty);
                btnOK.ClearValue(Button.ForegroundProperty);
                btnOK.IsEnabled = true;
            }
            else
            {
                btnOK.IsEnabled = false;
                btnOK.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,new DispatchedHandler(() =>
                    {
                        btnOK.BorderBrush = btnCancel.BorderBrush;
                        btnOK.Background = btnCancel.Background;
                        btnOK.Foreground = new SolidColorBrush(Colors.Gray);
                    }));
            }
        }
    }
}
