using System;
using System.Windows.Forms;
using System.Drawing;
using NotepadEnhanced.GUI.Forms;
using NotepadEnhanced.Localization;

namespace NotepadEnhanced
{
    class SystemTrayIcon : IDisposable
    {
        private readonly MainForm _frmMain;
        private readonly NotifyIcon _notifyIcon;

        public SystemTrayIcon(MainForm frmMain)
        {
            _frmMain = frmMain;
            _notifyIcon = GetNotifyIcon();
        }

        /// <summary>
        /// Hide the form and show the system tray icon
        /// </summary>
        public void MinimizeToTray()
        {
            _frmMain.Hide();
            _notifyIcon.Visible = true;
        }

        public NotifyIcon GetNotifyIcon()
        {
            NotifyIcon notifyIcon = new NotifyIcon
                {
                    Icon = new Icon(_frmMain.Icon, new Size(16, 16)),
                    ContextMenuStrip = GetContextMenuStrip(),
                    Text = Application.ProductName
                };

            // Th icon has to be reconstrcuted at a specific size or it will look wrong
            notifyIcon.MouseClick += _notifyIcon_Click;
            return notifyIcon;
        }

        private ContextMenuStrip GetContextMenuStrip()
        {
            var menuStrip = new ContextMenuStrip();
            menuStrip.Items.Add(Strings.CmsiShowText, null, cmsiShow_Click);
            menuStrip.Items.Add(new ToolStripSeparator());
            menuStrip.Items.Add(Strings.CmsiExitText, null, cmsiExit_Click);
            return menuStrip;
        }

        private void _notifyIcon_Click(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                UnMinimizeFromTray();
            }
        }

        private void cmsiShow_Click(object sender, EventArgs e)
        {
            UnMinimizeFromTray();
        }

        public void UnMinimizeFromTray()
        {
            if (_frmMain.Visible) return;
            _notifyIcon.Visible = false;
            _frmMain.Show();
        }

        private void cmsiExit_Click(object sender, EventArgs e)
        {
            _frmMain.Close();
        }

        public void Dispose()
        {
            _notifyIcon.Dispose();
        }
    }
}
