﻿using System;
using System.Collections.Generic;

namespace EV3RC.Services.KeyboardHook
{
    public class KeyboardHook : IKeyboardHook, IDisposable
    {
        private KeyboardListener _listener = null;

        public KeyboardHook()
        {
        }

        public IEnumerable<int> KeysPressed { get; private set; }

        public event EventHandler<KeyPressedEventArgs> OnKeyPressed;

        public void Start()
        {
            Stop();

            _listener = new KeyboardListener();
            _listener.KeyPressChanged += OnKeyPressChanged;
        }

        public void Stop()
        {
            if (_listener != null)
            {
                _listener.KeyPressChanged -= OnKeyPressChanged;
                _listener.Dispose();
                _listener = null;
            }
        }

        private void OnKeyPressChanged(object sender, KeyboardListener.KeyPressChangedEventArgs args)
        {
            KeysPressed = args.Keys;
            OnKeyPressed?.Invoke(this,
                                 new KeyPressedEventArgs
                                 {
                                     Keys = args.Keys
                                 });
        }

        public void Dispose()
        {
            Stop();
        }
    }
}