using MagicCarpetContracts.Enums; using MagicCarpetContracts.Exceptions; using MagicCarpetContracts.Extensions; using MagicCarpetContracts.Infrastructure; using MagicCarpetContracts.Infrastructure.PostConfigurations; using Microsoft.Extensions.Configuration; using Newtonsoft.Json.Linq; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using MagicCarpetContracts.Resources; using Microsoft.Extensions.Localization; using MagicCarpetContracts.Mapper; namespace MagicCarpetContracts.DataModels; internal class PostDataModel(string postId, string postName, PostType postType, PostConfiguration configuration) : IValidation { [AlternativeName("PostId")] public string Id { get; private set; } = postId; public string PostName { get; private set; } = postName; public PostType PostType { get; private set; } = postType; [AlternativeName("Configuration")] [AlternativeName("ConfigurationJson")] [PostProcessing(MappingCallMethodName = "ParseJson")] public PostConfiguration ConfigurationModel { get; private set; } = configuration; public PostDataModel() : this(string.Empty, string.Empty, PostType.None, null) { } public PostDataModel(string postId, string postName) : this(postId, postName, PostType.None, new PostConfiguration() { Rate = 10 }) { } public void Validate(IStringLocalizer localizer) { if (Id.IsEmpty()) throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "Id")); if (!Id.IsGuid()) throw new ValidationException(string.Format(localizer["ValidationExceptionMessageNotAId"], "Id")); if (PostName.IsEmpty()) throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "PostName")); if (PostType == PostType.None) throw new ValidationException(string.Format(localizer["ValidationExceptionMessageEmptyField"], "PostType")); if (ConfigurationModel is null) throw new ValidationException(string.Format(localizer["ValidationExceptionMessageNotInitialized"], "ConfigurationModel")); if (ConfigurationModel!.Rate <= 0) throw new ValidationException(string.Format(localizer["ValidationExceptionMessageLessOrEqualZero"], "Rate")); } private PostConfiguration? ParseJson(object json) { if (json is PostConfiguration config) { return config; } if (json is string) { var obj = JToken.Parse((string)json); var type = obj.Value("Type"); switch (type) { case nameof(TravelAgentPostConfiguration): ConfigurationModel = JsonConvert.DeserializeObject((string)json); break; case nameof(ChiefPostConfiguration): ConfigurationModel = JsonConvert.DeserializeObject((string)json); break; default: ConfigurationModel = JsonConvert.DeserializeObject((string)json); break; } return ConfigurationModel; } return null; } }