using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Vinno.IUS.Common.Log;
using Vinno.IUS.Common.Network.Leaf;
using Vinno.IUS.Common.Network.Transfer;
using Vinno.vCloud.Protocol.Messages.Client.Login;
using Vinno.vCloud.Protocol.Messages.Common;
namespace Vinno.vCloud.Common.FIS
{
internal class HeartRateKeeper
{
private readonly string _sessionId;
private readonly ClientLeaf _leaf;
private readonly ManualResetEvent _waitEvent = new ManualResetEvent(false);
private readonly int _heartRate;
public HeartRateKeeper(string sessionId, ClientLeaf leaf, int heartRateCycle)
{
_sessionId = sessionId;
_leaf = leaf;
_heartRate = heartRateCycle;
}
///
/// Start the Heartrate to keep the session available.
///
public void Start()
{
DoHeartRate();
}
///
/// Stop the Heartrate
///
public void Stop()
{
_waitEvent.Set();
}
///
/// Do HartRate
///
///
private void DoHeartRate()
{
Task.Run(() =>
{
while (!_waitEvent.WaitOne(TimeSpan.FromMinutes(_heartRate)))
{
try
{
using (var request = MessagePool.GetMessage())
{
request.AccountSessionId = _sessionId;
var result = ResultMessage.Convert(_leaf.Send(request));
if (result == null || result.ResultCode != OKResult.Code)
{
throw new InvalidDataException();
}
}
}
catch (Exception ex)
{
Logger.WriteLineError($"HeartRateKeeper Do Heart Rate Error:{ex}");
}
}
});
}
}
}