using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using Gma.System.MouseKeyHook;

namespace AnimeTiddiesHotkey {
    internal static class Program {
        private static IKeyboardMouseEvents _globalHook;
        private static NotifyIcon _trayIcon;
        private static bool _quiet = false;
        
        [STAThreadAttribute]
        private static void Main(string[] args) {
            _globalHook = Hook.GlobalEvents();
            _globalHook.OnCombination(new List<KeyValuePair<Combination, Action>>(new [] {
                new KeyValuePair<Combination, Action>(Combination.FromString("ControlKey+ShiftKey+R"), Application.Exit),
                new KeyValuePair<Combination, Action>(Combination.FromString("ControlKey+ShiftKey+E"), SetClipboard),
                new KeyValuePair<Combination, Action>(Combination.FromString("ControlKey+ShiftKey+M"), () => ToggleQuite(null, null))
            }));

            _trayIcon = new NotifyIcon {
                Visible = true,
                Icon = SystemIcons.Application
            };
            _trayIcon.Click += ShowHelp;
            _trayIcon.DoubleClick += ToggleQuite;
            
            var handle = GetConsoleWindow();
            ShowWindow(handle, 0);
            
            ShowHelp(null, null);
            Application.Run();
            ShowPopup("Goodbye");
        }
        
        [DllImport("kernel32.dll")]
        static extern IntPtr GetConsoleWindow();

        [DllImport("user32.dll")]
        static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

        private static void ShowHelp(object _, EventArgs __) {
            ShowPopup("Ctrl+Shift+R - Exit\nCtrl+Shift+E - Roll\nCtrl+Shift+M - Toggle quiet");
        }
        
        private static void ToggleQuite(object _, EventArgs __) {
            var oq = _quiet;
            _quiet = false;
            ShowPopup(_quiet? "Now I am loud!" : "Now I am silent!");
            _quiet = oq;
                
            _quiet = !_quiet;
        }

        private static void ShowPopup(string message, int timeout=1000, ToolTipIcon icon=ToolTipIcon.Info) {
            if (_quiet) return;
            _trayIcon.ShowBalloonTip(timeout, "Anime Tiddies trigger", message, icon);
        }

        private static void SetClipboard() {
            var roll = new Random().Next(0, ImagesStrings.bigTiddiesDragons.Length);
            ShowPopup($"Roll: {roll}");
            var image = Base64ToImage(ImagesStrings.bigTiddiesDragons[roll]);
            Clipboard.SetImage(image);
        }

        private static Image Base64ToImage(string base64String)
        {
            var imageBytes = Convert.FromBase64String(base64String);
            using var ms = new MemoryStream(imageBytes, 0, imageBytes.Length);
            var image = Image.FromStream(ms, true);
            return image;
        }
    }
}