using System;
using System.Runtime.InteropServices;
using Decal.Interop.Input;

namespace Decal.DecalInput
{
    [ComVisible(true)]
    [Guid("79497C87-92E1-416B-AE5C-9D6C4C59133C")]
    [ClassInterface(ClassInterfaceType.None)]
    [ComSourceInterfaces(typeof(ITimerEvents))]
    [ProgId("DecalInput.Timer")]
    public class TimerImpl : IDecalTimer
    {
        private object _tag;
        private bool _running;
        private int _interval;
        private uint _startTime;

        public event ITimerEvents_TimeoutEventHandler Timeout;

        public void Start(int Interval)
        {
            _interval = Interval;
            _startTime = GetTickCount();
            _running = true;

            InputServiceImpl.Instance?.RegisterTimer(this);
        }

        public void Stop()
        {
            _running = false;
            InputServiceImpl.Instance?.UnregisterTimer(this);
        }

        public object Tag
        {
            get => _tag;
            set => _tag = value;
        }

        public bool Running => _running;

        internal bool CheckTimeout(uint currentTime)
        {
            if (!_running) return false;
            if (currentTime - _startTime >= (uint)_interval)
            {
                _startTime = currentTime;
                Timeout?.Invoke((Timer)(object)this);
                return true;
            }
            return false;
        }

        [DllImport("kernel32.dll")]
        private static extern uint GetTickCount();
    }
}
