using System;
using Vinno.IUS.Common.Log;
using Vinno.IUS.Common.Network.Leaf;
using Vinno.IUS.Common.Network.Tcp;
using Vinno.IUS.Common.Network.Transfer;
using Vinno.vCloud.Protocol.Infrastructures;
using Vinno.vCloud.Protocol.Messages.Client;
using Vinno.vCloud.Protocol.Messages.Rtc;
namespace Vinno.vCloud.Common.FIS.LiveVideos
{
class RtcTerminalClient : IDisposable
{
private ClientLeaf _clientLeaf;
private ConnectionChecker _connectionKeeper;
///
/// Disconnected with chat
///
public event EventHandler Disconnected;
///
/// Chat room id = chat table id
///
public string ChatRoomId { get; }
public bool ClientIsOnline => _clientLeaf == null?false: _clientLeaf.Online;
public RtcTerminalClient(string url, string roomId)
{
ChatRoomId = roomId;
var tcpCreator = new TcpCreator(url);
Logger.WriteLineInfo($"RtcTerminalClient:{tcpCreator.Url}");
_clientLeaf = new ClientLeaf(new LeafIdContext(), LeafMode.Dual, tcpCreator);
if (!_clientLeaf.Online)
{
_clientLeaf.Close();
throw new Exception("RtcClient not connect");
}
_connectionKeeper = new ConnectionChecker(_clientLeaf,5);
_connectionKeeper.Offlined += OnOfflined;
_connectionKeeper.Start();
}
public void NotifyServerJoinRoomSuccess(string roomId, string accountId, AccountType accountType)
{
try
{
Logger.WriteLineInfo("RequestRtcChatLive Start");
if(!_clientLeaf.Online)
{
Logger.WriteLineError("RtcTerminalClient is not online");
return;
}
if (_clientLeaf.IsClosed)
{
Logger.WriteLineError("RtcTerminalClient is Closed");
return;
}
using (var request = MessagePool.GetMessage())
{
request.RoomId = roomId;
request.SubscriberId = accountId;
request.SubscriberType = accountType;
var result = _clientLeaf?.Send(request);
if (result != null)
{
var resultMessage = ResultMessage.Convert(result);
if (resultMessage != CCR.OK)
{
Logger.WriteLineError("RequestRtcChatLive Fail");
}
else
{
Logger.WriteLineInfo("RequestRtcChatLive Success");
}
}
}
}
catch (Exception ex)
{
Logger.WriteLineError($"RequestRtcChatLive error:{ex}");
}
}
private void OnOfflined(object sender, EventArgs e)
{
Disconnected?.Invoke(sender, ChatRoomId);
}
public void Dispose()
{
if (_connectionKeeper != null)
{
_connectionKeeper.Offlined -= OnOfflined;
_connectionKeeper.Stop();
_connectionKeeper = null;
}
if (_clientLeaf != null)
{
_clientLeaf.Close();
_clientLeaf = null;
}
// _platformManager.LivePlayManager.UnRegisterChatVideo();
}
}
}