using RyzStudio.Windows.Forms;
using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using Resources = AppLauncher.Properties.Resources20;

namespace AppLauncher.Windows.Forms
{
    public class TForm : Form
    {
        protected readonly Color borderColour = Color.FromArgb(235, 234, 233);
        protected readonly int borderWidth = 1;

        protected readonly int resizeBorderWidth = 3;

        protected readonly Color backColour = Color.FromArgb(255, 255, 255);

        protected readonly Color titleBackColour = Color.FromArgb(235, 234, 233);
        protected readonly Color titleBorderColour = Color.FromArgb(200, 198, 196);
        protected readonly Color titleColour = Color.FromArgb(102, 102, 102);
        protected readonly int titleBarHeight = 54;
        protected Font titleFont = null;
        protected int titleFontTop = 0;

        protected readonly int titleBarIconSize = 20;
        protected readonly int titleBarIconMargin = 8;

        protected bool isDragging = false;
        protected Point startPosition = new Point();
        protected Point startWindowSize = new Point();

        protected bool isBusy = false;

        protected Image appIcon = null;
        protected int appIconTop = 0;

        protected bool isMinimiseEnabled = true;
        protected bool isMaximiseEnabled = true;
        protected bool closeOnMinimise = false;
        protected bool enableMinimiseMenu = true;
        protected bool enableMaximiseMenu = true;
        protected bool enableCloseMenu = true;

        protected MouseEventHandler minimiseMenuEvent = null;
        protected MouseEventHandler maximiseMenuEvent = null;
        protected MouseEventHandler closeMenuEvent = null;

        private IContainer components;


        public TForm() : base()
        {
            InitializeComponent();

            if (!this.DesignMode)
            {
                this.FormBorderStyle = FormBorderStyle.None;
                this.StartPosition = FormStartPosition.Manual;
            }

            this.AutoScaleMode = AutoScaleMode.None;
            this.BackColor = backColour;
            this.Padding = new Padding(0);
            this.DoubleBuffered = true;

            this.MouseDown += new MouseEventHandler(form_MouseDown);
            this.MouseMove += new MouseEventHandler(form_MouseMove);
            this.MouseUp += new MouseEventHandler(form_MouseUp);
            this.PreviewKeyDown += new PreviewKeyDownEventHandler(form_PreviewKeyDown);
        }

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

            this.Text = Application.ProductName;

            initialiseLoadComponent();

            if (appIcon != null) appIconTop = (int)Math.Floor((decimal)(titleBarHeight - appIcon.Height) / 2) + borderWidth;
            titleFont = new Font(this.Font.FontFamily, 10F);
            titleFontTop = (int)Math.Floor((decimal)(titleBarHeight - TextRenderer.MeasureText("#", titleFont).Height) / 2) + borderWidth;

        }

        protected override void OnMouseClick(MouseEventArgs e)
        {
            base.OnMouseClick(e);

            bool isLabel = ((e.Location.X >= 0) && (e.Location.X <= this.Width) && (e.Location.Y >= 0) && (e.Location.Y <= titleBarHeight));

            if (e.Button == MouseButtons.Left)
            {
                if (isLabel)
                {
                    // do nothing
                }
                else
                {
                    // do nothing
                }
            }
            else if (e.Button == MouseButtons.Right)
            {
                if (isLabel)
                {
                    if (this.TitleContextMenuStrip != null)
                    {
                        this.TitleContextMenuStrip.Show(this, e.Location);
                    }
                }
                else
                {
                    // do nothing
                }
            }
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);

            Graphics g = e.Graphics;
            Rectangle area = new Rectangle(this.DisplayRectangle.X, this.DisplayRectangle.Y, (this.DisplayRectangle.Width - borderWidth), (this.DisplayRectangle.Height - borderWidth));

            // border
            g.DrawRectangle(new Pen(borderColour, borderWidth), area);

            area.Inflate((-1 * borderWidth), (-1 * borderWidth));

            g.FillRectangle(new SolidBrush(titleBackColour), area.X, area.Y, (area.Width + area.X), titleBarHeight);
            g.DrawLine(new Pen(titleBorderColour, 1), area.X, (titleBarHeight + 1), (area.Width + area.X), (titleBarHeight + 1));

            if (!DesignMode)
            {
                //g.DrawImageUnscaled(appIcon, 17, appIconTop);
                g.DrawImage(appIcon, 17, appIconTop, appIcon.Width, appIcon.Height);

                TextRenderer.DrawText(g, this.Text, titleFont, new Point(58, titleFontTop), titleColour);
            }
        }

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

            this.Invalidate();
        }

        [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
        public override Color BackColor { get => base.BackColor; set => base.BackColor = value; }

        [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
        public new FormBorderStyle FormBorderStyle { get => base.FormBorderStyle; set => base.FormBorderStyle = value; }

        [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
        public new Padding Padding { get => base.Padding; set => base.Padding = value; }

        [Category("Appearance")]
        public ContextMenuStrip TitleContextMenuStrip { get; set; } = null;

        //[Browsable(false)]
        //public Image AppIcon { get; set; } = null;

        //[Browsable(false)]
        //public bool IsMaximiseEnabled { get; set; } = false;

        //protected Point DefaultLocation
        //{
        //    get
        //    {
        //        Point newPosition = new Point(Cursor.Position.X, Cursor.Position.Y);
        //        newPosition.X -= (this.Width / 2);
        //        newPosition.Y -= (this.Height / 2);

        //        newPosition.X = Math.Max(newPosition.X, Screen.PrimaryScreen.WorkingArea.Left);
        //        newPosition.Y = Math.Max(newPosition.Y, Screen.PrimaryScreen.WorkingArea.Top);

        //        return newPosition;
        //    }
        //}

        private void InitializeComponent()
        {
            this.components = new System.ComponentModel.Container();
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(TForm));
            this.SuspendLayout();
            //
            // AForm
            //
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
            this.Name = "Form";
            this.ResumeLayout(false);
        }

        private void form_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                isDragging = true;
                startPosition = e.Location;
                startWindowSize = new Point(this.Width, this.Height);
            }
        }

        private void form_MouseMove(object sender, MouseEventArgs e)
        {
            if (isDragging)
            {
                int x = (this.Location.X + (e.Location.X - startPosition.X));
                int y = (this.Location.Y + (e.Location.Y - startPosition.Y));

                //this.Location = validateFormLocation(x, y);
                this.Location = new Point(x, y);
            }
        }

        private void form_MouseUp(object sender, MouseEventArgs e)
        {
            isDragging = false;
        }

        private void form_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
        {
            if (e.KeyCode == Keys.Escape)
            {
                Application.Exit();
            }
        }

        protected virtual void initialiseLoadComponent()
        {
            if (DesignMode) return;

            // close
            TImageBox closeBox = generateToolbarImageBox();
            if (enableCloseMenu)
            {
                closeBox.Image = closeBox.ImageNormal = Resources.close;
                closeBox.ImageHover = Resources.close3;
                //closeBox.ImageSelected = null;
                closeBox.MouseClick += delegate (object sender, MouseEventArgs e)
                {
                    if (e.Button != MouseButtons.Left) return;

                    if (closeMenuEvent != null)
                    {
                        closeMenuEvent(sender, e);
                        return;
                    }

                    this.Close();
                };
            }
            else
            {
                closeBox.Image = closeBox.ImageNormal = closeBox.ImageHover = closeBox.ImageSelected = Resources.close;
            }

            closeBox.Left = this.DisplayRectangle.Width - closeBox.Width - 17;

            this.Controls.Add(closeBox);

            // maximise
            TImageBox maximiseBox = generateToolbarImageBox();
            if (enableMaximiseMenu)
            {
                maximiseBox.Image = maximiseBox.ImageNormal = (isMaximiseEnabled) ? Resources.maximise : Resources.empty;
                maximiseBox.ImageHover = (isMaximiseEnabled) ? Resources.maximise2 : Resources.empty;
                maximiseBox.ImageSelected = Resources.maximise3;
                maximiseBox.MouseClick += delegate (object sender, MouseEventArgs e)
                {
                    if (!(sender is TImageBox)) return;

                    TImageBox imageBox2 = (sender as TImageBox);

                    if (imageBox2 == null) return;

                    if (maximiseMenuEvent != null)
                    {
                        maximiseMenuEvent(sender, e);
                        return;
                    }

                    if (e.Button == MouseButtons.Left)
                    {
                        if (isMaximiseEnabled)
                        {
                            if (this.WindowState == FormWindowState.Maximized)
                            {
                                this.WindowState = FormWindowState.Normal;
                                imageBox2.Image = imageBox2.ImageNormal = Resources.maximise;
                            }
                            else
                            {
                                this.WindowState = FormWindowState.Maximized;
                                imageBox2.Image = imageBox2.ImageNormal = Resources.maximise2;
                            }
                        }
                    }
                    else if (e.Button == MouseButtons.Right)
                    {
                        this.TopMost = !this.TopMost;

                        if (this.TopMost)
                        {
                            imageBox2.Image = imageBox2.ImageNormal = Resources.maximise3;
                            imageBox2.ImageHover = (isMaximiseEnabled) ? Resources.maximise2 : Resources.maximise3;
                        }
                        else
                        {
                            imageBox2.Image = imageBox2.ImageNormal = (isMaximiseEnabled) ? Resources.maximise : Resources.empty;
                            imageBox2.ImageHover = (isMaximiseEnabled) ? Resources.maximise2 : Resources.empty;
                        }
                    }
                };
            }
            else
            {
                maximiseBox.Image = maximiseBox.ImageNormal = maximiseBox.ImageHover = maximiseBox.ImageSelected = Resources.maximise;
            }

            maximiseBox.Left = closeBox.Left - maximiseBox.Width - titleBarIconMargin;

            this.Controls.Add(maximiseBox);

            // minimise
            TImageBox minimiseBox = generateToolbarImageBox();
            if (enableMinimiseMenu)
            {
                minimiseBox.Image = minimiseBox.ImageNormal = (isMinimiseEnabled) ? Resources.minimise : Resources.empty;
                minimiseBox.ImageHover = (isMinimiseEnabled) ? Resources.minimise2 : Resources.empty;
                //minimiseBox.ImageSelected = null;
                minimiseBox.MouseClick += delegate (object sender, MouseEventArgs e)
                {
                    if (!isMinimiseEnabled) return;
                    if (e.Button != MouseButtons.Left) return;

                    if (minimiseMenuEvent != null)
                    {
                        minimiseMenuEvent(sender, e);
                        return;
                    }

                    if (closeOnMinimise)
                    {
                        this.Close();
                    }
                    else
                    {
                        this.WindowState = FormWindowState.Minimized;
                    }
                };
            }
            else
            {
                minimiseBox.Image = minimiseBox.ImageNormal = minimiseBox.ImageHover = minimiseBox.ImageSelected = Resources.minimise;
            }

            minimiseBox.Left = maximiseBox.Left - minimiseBox.Width - titleBarIconMargin;

            this.Controls.Add(minimiseBox);

            // resize
            UserControl uc1 = new UserControl()
            {
                Anchor = (AnchorStyles.Left | AnchorStyles.Bottom | AnchorStyles.Right),
                Height = resizeBorderWidth,
                Width = this.DisplayRectangle.Width - resizeBorderWidth,
                Left = 0,
                Top = this.DisplayRectangle.Height - resizeBorderWidth,
                BackColor = Color.Transparent,
                Cursor = Cursors.SizeNS
            };
            uc1.MouseDown += form_MouseDown;
            uc1.MouseUp += form_MouseUp;
            uc1.MouseMove += delegate (object sender, MouseEventArgs e)
            {
                if (isDragging)
                {
                    this.Size = new Size(startWindowSize.X, e.Y - startPosition.Y + this.Height);
                }
            };
            uc1.BringToFront();

            this.Controls.Add(uc1);

            UserControl uc2 = new UserControl()
            {
                Anchor = (AnchorStyles.Top | AnchorStyles.Right | AnchorStyles.Bottom),
                Height = this.DisplayRectangle.Height - resizeBorderWidth,
                Width = resizeBorderWidth,
                Left = this.DisplayRectangle.Width - resizeBorderWidth,
                Top = 0,
                BackColor = Color.Transparent,
                Cursor = Cursors.SizeWE
            };
            uc2.MouseDown += form_MouseDown;
            uc2.MouseUp += form_MouseUp;
            uc2.MouseMove += delegate (object sender, MouseEventArgs e)
            {
                if (isDragging)
                {
                    this.Size = new Size(e.X - startPosition.X + this.Width, startWindowSize.Y);
                }
            };
            uc2.BringToFront();

            this.Controls.Add(uc2);

            UserControl uc3 = new UserControl()
            {
                Anchor = (AnchorStyles.Bottom | AnchorStyles.Right),
                Height = resizeBorderWidth,
                Width = resizeBorderWidth,
                Left = this.DisplayRectangle.Width - resizeBorderWidth,
                Top = this.DisplayRectangle.Height - resizeBorderWidth,
                BackColor = Color.Transparent,
                Cursor = Cursors.SizeNWSE
            };
            uc3.MouseDown += form_MouseDown;
            uc3.MouseUp += form_MouseUp;
            uc3.MouseMove += delegate (object sender, MouseEventArgs e)
            {
                if (isDragging)
                {
                    this.Size = new Size((e.X - startPosition.X + this.Width), (e.Y - startPosition.Y + this.Height));
                }
            };
            uc3.BringToFront();

            this.Controls.Add(uc3);
        }

        protected TImageBox generateToolbarImageBox()
        {
            TImageBox imageBox = new TImageBox();
            imageBox.BackColor = Color.Transparent;
            imageBox.BackgroundImageLayout = ImageLayout.Center;
            imageBox.ErrorImage = null;
            //imageBox.Image = Resources.close;
            //imageBox.ImageHover = Resources.close2;
            //imageBox.ImageNormal = Resources.close;
            imageBox.ImageSelected = null;
            imageBox.IsSelected = false;
            //closeBox.Location = new System.Drawing.Point(169, 12);
            imageBox.Size = new System.Drawing.Size(titleBarIconSize, titleBarIconSize);
            imageBox.SizeMode = PictureBoxSizeMode.CenterImage;
            //imageBox.MouseClick += new MouseEventHandler(closeBox_MouseClick);
            //imageBox.Left = this.DisplayRectangle.Width - imageBox.Width - 17;
            imageBox.Top = (int)Math.Floor((decimal)(titleBarHeight - titleBarIconSize) / 2);
            imageBox.Anchor = (AnchorStyles.Top | AnchorStyles.Right);

            return imageBox;
        }

        //private void exitToolStripMenuItem_Click(object sender, EventArgs e) => this.Close();

        //private void notifyIcon1_MouseClick(object sender, MouseEventArgs e)
        //{
        //    if (e.Button == MouseButtons.Left)
        //    {
        //        this.Visible = !this.Visible;
        //    }

        //    //notifyIcon1.Visible = !this.Visible;
        //}


    }
}