using System;
using System.ComponentModel;
using System.Drawing;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;
using BookmarkManager.Services;
using bzit.bomg.Models;
using RyzStudio.Windows.Forms;
using RyzStudio.Windows.ThemedForms;
using RyzStudio.Windows.ThemedForms.ButtonTextBox;

namespace FizzyLauncher
{
    public class EditBookmarkForm : Form
    {
        private System.Windows.Forms.Label label1;
        private ThClearableTextBox textBox1;
        private Label label2;
        private Label label3;
        private ThToolbarMemoBox memoBox1;
        private Label label4;
        private ThHiButtonTextBox textBox2;
        private PictureBox pictureBox1;
        private ToolTip toolTip1;
        private System.ComponentModel.IContainer components;
        private ThClearableTextBox textBox3;
        private ThUserControl thUserControl1;
        private Label label5;


        private readonly WebProvider _webProvider;
        private BookmarkModel result = null;
        private RyzStudio.Windows.ThemedForms.Composite.DialogFooter dialogFooter1;
        private bool _isBusy = false;


        public EditBookmarkForm(BookmarkModel model = null)
        {
            InitializeComponent();

            UISetup.Dialog(this);

            this.Text = (result == null) ? "Add Bookmark" : "Edit Bookmark";

            result = model;

            _webProvider = new WebProvider();
            _webProvider.IgnoreSSL = true;

            if (result != null)
            {
                textBox1.Text = model.Title?.Trim() ?? string.Empty;
                textBox2.Text = model.Address?.Trim() ?? string.Empty;
                textBox3.Text = model.Description?.Trim() ?? string.Empty;

                try
                {
                    if (model.Icon != null)
                    {
                        if (model.Icon.Width > 16)
                        {
                            model.Icon = RyzStudio.Drawing.ImageEditor.Resize(model.Icon, 16, 16);
                        }
                    }

                    pictureBox1.Image = model.Icon;
                }
                catch (Exception)
                {
                    pictureBox1.Image = model.Icon = null;
                }

                memoBox1.Text = model.Notes?.Trim() ?? string.Empty;
            }
        }

        private void InitializeComponent()
        {
            components = new Container();
            label1 = new Label();
            textBox1 = new ThClearableTextBox();
            label2 = new Label();
            label3 = new Label();
            memoBox1 = new ThToolbarMemoBox();
            label4 = new Label();
            textBox2 = new ThHiButtonTextBox();
            pictureBox1 = new PictureBox();
            toolTip1 = new ToolTip(components);
            textBox3 = new ThClearableTextBox();
            thUserControl1 = new ThUserControl();
            label5 = new Label();
            dialogFooter1 = new RyzStudio.Windows.ThemedForms.Composite.DialogFooter();
            ((ISupportInitialize)pictureBox1).BeginInit();
            SuspendLayout();
            //
            // label1
            //
            label1.AutoSize = true;
            label1.BackColor = Color.Transparent;
            label1.ForeColor = SystemColors.ControlText;
            label1.Location = new Point(10, 21);
            label1.Margin = new Padding(0);
            label1.Name = "label1";
            label1.Padding = new Padding(0, 8, 0, 0);
            label1.Size = new Size(29, 23);
            label1.TabIndex = 153;
            label1.Text = "Title";
            label1.TextAlign = ContentAlignment.MiddleLeft;
            //
            // textBox1
            //
            textBox1.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
            textBox1.BackColor = Color.Transparent;
            textBox1.ClearedValue = "";
            textBox1.EnableReactiveVisual = true;
            textBox1.Font = new Font("Segoe UI", 9F);
            textBox1.Icon = "O";
            textBox1.IconSize = 13F;
            textBox1.Location = new Point(109, 20);
            textBox1.Name = "textBox1";
            textBox1.Size = new Size(260, 32);
            textBox1.TabIndex = 0;
            textBox1.TabStop = false;
            textBox1.UseSystemPasswordChar = false;
            //
            // label2
            //
            label2.AutoSize = true;
            label2.BackColor = Color.Transparent;
            label2.ForeColor = SystemColors.ControlText;
            label2.Location = new Point(10, 61);
            label2.Margin = new Padding(0);
            label2.Name = "label2";
            label2.Padding = new Padding(0, 8, 0, 0);
            label2.Size = new Size(49, 23);
            label2.TabIndex = 193;
            label2.Text = "Address";
            label2.TextAlign = ContentAlignment.MiddleLeft;
            //
            // label3
            //
            label3.AutoSize = true;
            label3.BackColor = Color.Transparent;
            label3.ForeColor = SystemColors.ControlText;
            label3.Location = new Point(10, 104);
            label3.Margin = new Padding(0);
            label3.Name = "label3";
            label3.Padding = new Padding(0, 8, 0, 0);
            label3.Size = new Size(67, 23);
            label3.TabIndex = 195;
            label3.Text = "Description";
            label3.TextAlign = ContentAlignment.MiddleLeft;
            //
            // memoBox1
            //
            memoBox1.AllowDrop = true;
            memoBox1.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right;
            memoBox1.BackColor = Color.Transparent;
            memoBox1.ClearedValue = "";
            memoBox1.EnableReactiveVisual = true;
            memoBox1.Font = new Font("Segoe UI", 9F);
            memoBox1.Location = new Point(110, 196);
            memoBox1.Name = "memoBox1";
            memoBox1.ReadOnly = false;
            memoBox1.ScrollBars = ScrollBars.Vertical;
            memoBox1.Size = new Size(259, 232);
            memoBox1.TabIndex = 3;
            memoBox1.TabStop = false;
            memoBox1.WordWrap = false;
            //
            // label4
            //
            label4.AutoSize = true;
            label4.BackColor = Color.Transparent;
            label4.ForeColor = SystemColors.ControlText;
            label4.Location = new Point(10, 196);
            label4.Margin = new Padding(0);
            label4.Name = "label4";
            label4.Padding = new Padding(0, 8, 0, 0);
            label4.Size = new Size(38, 23);
            label4.TabIndex = 198;
            label4.Text = "Notes";
            label4.TextAlign = ContentAlignment.MiddleLeft;
            //
            // textBox2
            //
            textBox2.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
            textBox2.BackColor = Color.Transparent;
            textBox2.EnableReactiveVisual = true;
            textBox2.Font = new Font("Segoe UI", 9F);
            textBox2.Icon = "M";
            textBox2.IconSize = 13F;
            textBox2.Location = new Point(110, 62);
            textBox2.Name = "textBox2";
            textBox2.Size = new Size(259, 32);
            textBox2.TabIndex = 1;
            textBox2.TabStop = false;
            textBox2.UseSystemPasswordChar = false;
            textBox2.OnButtonClick += textBox2_OnButtonClick;
            //
            // pictureBox1
            //
            pictureBox1.BackColor = Color.White;
            pictureBox1.ErrorImage = null;
            pictureBox1.InitialImage = null;
            pictureBox1.Location = new Point(113, 150);
            pictureBox1.Name = "pictureBox1";
            pictureBox1.Size = new Size(32, 32);
            pictureBox1.SizeMode = PictureBoxSizeMode.CenterImage;
            pictureBox1.TabIndex = 201;
            pictureBox1.TabStop = false;
            pictureBox1.MouseClick += pictureBox1_MouseClick;
            pictureBox1.MouseDoubleClick += pictureBox1_MouseDoubleClick;
            //
            // textBox3
            //
            textBox3.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
            textBox3.BackColor = Color.Transparent;
            textBox3.ClearedValue = "";
            textBox3.EnableReactiveVisual = true;
            textBox3.Font = new Font("Segoe UI", 9F);
            textBox3.Icon = "O";
            textBox3.IconSize = 13F;
            textBox3.Location = new Point(109, 104);
            textBox3.Name = "textBox3";
            textBox3.Size = new Size(260, 32);
            textBox3.TabIndex = 203;
            textBox3.TabStop = false;
            textBox3.UseSystemPasswordChar = false;
            //
            // thUserControl1
            //
            thUserControl1.BackColor = Color.Transparent;
            thUserControl1.EnableReactiveVisual = true;
            thUserControl1.Location = new Point(109, 146);
            thUserControl1.Name = "thUserControl1";
            thUserControl1.Size = new Size(40, 40);
            thUserControl1.TabIndex = 204;
            thUserControl1.TabStop = false;
            //
            // label5
            //
            label5.AutoSize = true;
            label5.BackColor = Color.Transparent;
            label5.ForeColor = SystemColors.ControlText;
            label5.Location = new Point(10, 146);
            label5.Margin = new Padding(0);
            label5.Name = "label5";
            label5.Padding = new Padding(0, 8, 0, 0);
            label5.Size = new Size(30, 23);
            label5.TabIndex = 195;
            label5.Text = "Icon";
            label5.TextAlign = ContentAlignment.MiddleLeft;
            //
            // dialogFooter1
            //
            dialogFooter1.BackColor = Color.FromArgb(240, 240, 240);
            dialogFooter1.Button1Text = "&OK";
            dialogFooter1.Dialog = this;
            dialogFooter1.Dock = DockStyle.Bottom;
            dialogFooter1.IsBusy = false;
            dialogFooter1.Location = new Point(0, 437);
            dialogFooter1.Name = "dialogFooter1";
            dialogFooter1.Size = new Size(384, 84);
            //
            // EditBookmarkForm
            //
            AutoScaleDimensions = new SizeF(7F, 15F);
            AutoScaleMode = AutoScaleMode.Font;
            BackColor = Color.White;
            ClientSize = new Size(384, 521);
            Controls.Add(dialogFooter1);
            Controls.Add(textBox3);
            Controls.Add(pictureBox1);
            Controls.Add(textBox2);
            Controls.Add(memoBox1);
            Controls.Add(label4);
            Controls.Add(label5);
            Controls.Add(label3);
            Controls.Add(label2);
            Controls.Add(textBox1);
            Controls.Add(label1);
            Controls.Add(thUserControl1);
            KeyPreview = true;
            MinimumSize = new Size(400, 560);
            Name = "EditBookmarkForm";
            Text = "Edit Bookmark";
            ((ISupportInitialize)pictureBox1).EndInit();
            ResumeLayout(false);
            PerformLayout();
        }

        protected override void OnShown(EventArgs e)
        {
            base.OnShown(e);

            textBox2.Focus();
        }

        protected override void OnClosing(CancelEventArgs e)
        {
            base.OnClosing(e);

            if (this.IsBusy)
            {
                e.Cancel = true;
            }
        }

        public BookmarkModel Result
        {
            get
            {
                if (result == null)
                {
                    result = new BookmarkModel();
                }

                result.Title = textBox1.Text?.Trim() ?? string.Empty;
                result.Address = textBox2.Text?.Trim() ?? string.Empty;
                result.Description = textBox3.Text?.Trim() ?? string.Empty;

                try
                {
                    result.Icon = pictureBox1.Image;
                }
                catch (Exception)
                {
                    // do nothing
                }

                result.Notes = memoBox1.Text?.Trim() ?? string.Empty;

                return result;
            }
        }

        protected bool IsBusy
        {
            get => _isBusy;
            set
            {
                _isBusy = value;

                UIControl.SetEnable(textBox1, !this.IsBusy);
                UIControl.SetEnable(textBox2, !this.IsBusy);
                UIControl.SetEnable(textBox3, !this.IsBusy);
                dialogFooter1.IsBusy = _isBusy;
                UIControl.SetEnable(memoBox1, !this.IsBusy);
            }
        }


        private async void textBox2_OnButtonClick(object sender, EventArgs e)
        {
            await InvalidateWebPage(textBox2.Text, true, true, true);

            textBox2.Focus();
        }

        private async void pictureBox1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                await InvalidateWebPage(textBox2.Text, false, false, true);
            }
        }

        private void pictureBox1_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                pictureBox1.Image = null;
            }
        }

        private async Task InvalidateWebPage(string url, bool updateTitle, bool updateDescription, bool updateIcon)
        {
            if (string.IsNullOrWhiteSpace(url))
            {
                return;
            }

            if (this.IsBusy)
            {
                return;
            }

            this.IsBusy = true;

            if (!url.StartsWith("http://", StringComparison.CurrentCultureIgnoreCase) && !url.StartsWith("https://", StringComparison.CurrentCultureIgnoreCase))
            {
                url = "http://" + url;
            }

            var document = await _webProvider.RetrieveHtmlDocument(url);
            if (document == null)
            {
                this.IsBusy = false;
                return;
            }

            if (updateTitle)
            {
                textBox1.Text = _webProvider.ParseTitle(document);
            }

            if (updateDescription)
            {
                textBox3.Text = _webProvider.ParseDescription(document);
            }

            if (updateIcon)
            {
                try
                {
                    pictureBox1.Image = await _webProvider.RetrieveImage(url, document);
                    if (pictureBox1.Image != null)
                    {
                        if (pictureBox1.Image.Width > 16)
                        {
                            pictureBox1.Image = RyzStudio.Drawing.ImageEditor.Resize(pictureBox1.Image, 16, 16);
                        }
                    }
                }
                catch (Exception)
                {
                    pictureBox1.Image = null;
                }
            }

            this.IsBusy = false;
        }

    }
}