using Aurora.Api;
using Aurora.Api.Devices;
using DataHub;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Linq;
using System.Threading.Tasks;
namespace VisionCommon.DB {
///
/// 제너릭 타입의 공변성 미지원을 해결하기 위한 공통 인터페이스
///
public interface IVisionDBAgent { }
public abstract class VisionDBAgentBase : IVisionDBAgent where T : IMongoItemEntity {
internal eVisionDBKey _Key;
internal readonly DataHubService _Service;
internal static Logger _Logger;
private static IDisposable _EventDisposable;
public VisionDBAgentBase(eVisionDBKey dbKey) {
_Key = dbKey;
_Logger = new Logger("DB_"+ dbKey.ToString());
_Service = VisionEnv.AuroraEnv.DeviceManager.GetDevice(dbKey.ToString()) as DataHubService;
SetObservable();
}
#region EventObservables
internal virtual void SetObservable() {
if (_Service != null) {
VisionEnv.AuroraEnv.EventObservable.AsObservable(AuroraSysEvent.SYS_DEVICE_ACTIVATED)
.Select(x => x.Param as string).Where(x=> x==_Key.ToString()).Subscribe(x => OnDBActivated());
VisionEnv.AuroraEnv.EventObservable.AsObservable(AuroraSysEvent.SYS_DEVICE_DEACTIVATED)
.Select(x => x.Param as string).Where(x => x == _Key.ToString()).Subscribe(x => OnDBDeActivated());
}
}
internal virtual void OnDBActivated() { }
internal virtual void OnDBDeActivated() { }
#endregion
#region UtilMethods
public void SetDataAsync(T data) {
if (CheckServiceActivate()) {
_Service.AddItemAsync(data);
}
}
public void SetData(T data) {
if (CheckServiceActivate()) {
_Service.AddItem(data);
}
}
public async Task> GetDataAsync(T data, QueryOption queryOption) {
if (CheckServiceActivate()) {
return await _Service.GetDataAsync(queryOption);
}
return null;
}
public IEnumerable GetData(T data, QueryOption queryOption) {
if (CheckServiceActivate()) {
return _Service.GetData(queryOption);
}
return null;
}
#endregion
#region private util methods
internal bool CheckServiceActivate() {
if(_Service == null) {
_Logger.E("Service is null, Not Register Service. Check the registerService key");
return false;
}
else if(!_Service.IsActivated) {
_Logger.E("Service is not activated!!");
return false;
}else {
return true;
}
}
#endregion
}
}