using Caspian.WorkflowFramework.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.Json; using System.Text.Json.Nodes; using System.Threading.Tasks; namespace Caspian.WorkflowFramework.Utility { public static class ConversionExtensions { public static WorkflowModel ConvertToWorkflowModel(this Dictionary dictionary) { var workflowModel = new WorkflowModel(); if (dictionary == null || dictionary.Count == 0) return workflowModel; //Map dictionary values to WorkflowModel properties workflowModel.InstanceId = dictionary.ContainsKey(nameof(workflowModel.InstanceId)) ? dictionary[nameof(workflowModel.InstanceId)]?.ToString() : null; workflowModel.Name = dictionary.ContainsKey(nameof(workflowModel.Name)) ? dictionary[nameof(workflowModel.Name)]?.ToString() : null; workflowModel.IsComplete = dictionary.ContainsKey(nameof(workflowModel.IsComplete)) ? bool.TryParse(dictionary[nameof(workflowModel.IsComplete)]?.ToString(), out var isComplete) && isComplete : false; workflowModel.UserId = dictionary.ContainsKey(nameof(workflowModel.UserId)) ? long.TryParse(dictionary[nameof(workflowModel.UserId)]?.ToString(), out var userId) ? userId : (long?)null : null; //CurrentPageData if (dictionary.TryGetValue(nameof(workflowModel.CurrentPageData), out var currentPageDataObj) && currentPageDataObj is not null) { switch (currentPageDataObj) { case JsonElement je: workflowModel.CurrentPageData = je; break; case JsonNode node: // .NET 6+ workflowModel.CurrentPageData = JsonSerializer.SerializeToElement(node); break; case string s: // اگر به صورت string JSON ذخیره شده workflowModel.CurrentPageData = JsonSerializer.Deserialize(s); break; default: // هر نوع دیگری: serialize و تبدیل به JsonElement workflowModel.CurrentPageData = JsonSerializer.SerializeToElement(currentPageDataObj); break; } } else { workflowModel.CurrentPageData = null; } //NextPageData if (dictionary.TryGetValue(nameof(workflowModel.NextPageData), out var nextPageDataObj) && nextPageDataObj is not null) { switch (nextPageDataObj) { case JsonElement je: workflowModel.NextPageData = je; break; case JsonNode node: // .NET 6+ workflowModel.NextPageData = JsonSerializer.SerializeToElement(node); break; case string s: // اگر به صورت string JSON ذخیره شده workflowModel.NextPageData = JsonSerializer.Deserialize(s); break; default: // هر نوع دیگری: serialize و تبدیل به JsonElement workflowModel.NextPageData = JsonSerializer.SerializeToElement(nextPageDataObj); break; } } else { workflowModel.NextPageData = null; } workflowModel.NextPageUrl = dictionary.ContainsKey(nameof(workflowModel.NextPageUrl)) ? dictionary[nameof(workflowModel.NextPageUrl)]?.ToString() : null; workflowModel.NextPageEventName = dictionary.ContainsKey(nameof(workflowModel.NextPageEventName)) ? dictionary[nameof(workflowModel.NextPageEventName)]?.ToString() : null; return workflowModel; } } }