using Serein.Library.Api;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace Serein.Library
{
///
/// 全局运行环境
///
public static class SereinEnv
{
private static IFlowEnvironment environment;
#region 全局数据(暂时使用静态全局变量)
///
/// 记录全局数据
///
private static ConcurrentDictionary EnvGlobalData { get; } = new ConcurrentDictionary();
///
/// 添加或更新全局数据
///
///
///
///
public static void AddOrUpdateFlowGlobalData(string name, object data)
{
SereinEnv.EnvGlobalData.AddOrUpdate(name, data, (k, o) => data);
}
/*///
/// 更改某个数据的名称
///
/// 旧名称
/// 新名称
///
public static bool ChangeNameFlowGlobalData(string oldName, string newName)
{
if (string.IsNullOrEmpty(oldName) || string.IsNullOrEmpty(newName))
{
return false;
}
// 确保存在,然后尝试移除
if (SereinEnv.EnvGlobalData.ContainsKey(oldName)
&& SereinEnv.EnvGlobalData.TryRemove(oldName, out var data))
{
SereinEnv.EnvGlobalData.AddOrUpdate(newName, data, (k, o) => data);
return true;
}
else
{
return false;
}
}*/
///
/// 获取全局数据
///
///
///
public static object GetFlowGlobalData(string name)
{
if (!string.IsNullOrEmpty(name) && SereinEnv.EnvGlobalData.TryGetValue(name, out var data))
{
return data;
}
else
{
return null;
}
}
///
/// 清空全局数据
///
///
public static void ClearFlowGlobalData()
{
foreach (var nodeObj in EnvGlobalData.Values)
{
if (nodeObj != null)
{
if (typeof(IDisposable).IsAssignableFrom(nodeObj?.GetType()) && nodeObj is IDisposable disposable)
{
disposable?.Dispose();
}
}
else
{
}
}
EnvGlobalData.Clear();
return;
}
#endregion
///
/// 设置运行流程
///
///
public static void SetEnv(IFlowEnvironment environment)
{
if (environment != null)
{
SereinEnv.environment = environment;
}
}
///
/// 输出内容
///
/// 类型
/// 内容
/// 级别
public static void WriteLine(InfoType type, string message, InfoClass @class = InfoClass.General)
{
Debug.WriteLine($"{type} : {message}");
Console.WriteLine($"{type} : {message}");
SereinEnv.environment?.WriteLine(type,message,@class);
}
///
/// 输出异常信息
///
///
///
public static void WriteLine(Exception ex, InfoClass @class = InfoClass.General)
{
if(@class == InfoClass.Debug)
{
SereinEnv.environment.WriteLine(InfoType.ERROR, ex.ToString(), @class);
}
else
{
SereinEnv.environment.WriteLine(InfoType.ERROR, ex.Message, @class);
}
}
///
/// 尝试在UI线程上触发事件
///
///
///
public async static Task TriggerEvent(Action action)
{
if (environment is null)
{
action?.Invoke();
}
else
{
var uco = environment.UIContextOperation;
if (uco is null)
{
action?.Invoke();
}
else
{
await uco.InvokeAsync(() =>
{
action?.Invoke();
});
}
}
}
}
}