using System;
using Microsoft.Win32;

namespace AxCopilot.Services;

public sealed class SessionTrackingService : IDisposable
{
	private DateTime? _unlockTime;

	private bool _disposed;

	public SessionTrackingService()
	{
		_unlockTime = DateTime.Now;
		SystemEvents.SessionSwitch += OnSessionSwitch;
	}

	private void OnSessionSwitch(object sender, SessionSwitchEventArgs e)
	{
		if (e.Reason == SessionSwitchReason.SessionLock)
		{
			FlushActiveTime();
		}
		else if (e.Reason == SessionSwitchReason.SessionUnlock || e.Reason == SessionSwitchReason.SessionLogon)
		{
			_unlockTime = DateTime.Now;
		}
	}

	private void FlushActiveTime()
	{
		if (_unlockTime.HasValue)
		{
			int num = (int)(DateTime.Now - _unlockTime.Value).TotalSeconds;
			if (num > 0)
			{
				UsageStatisticsService.AddActiveSeconds(num);
			}
			_unlockTime = null;
		}
	}

	public void Dispose()
	{
		if (!_disposed)
		{
			_disposed = true;
			FlushActiveTime();
			SystemEvents.SessionSwitch -= OnSessionSwitch;
		}
	}
}
