using System; using System.Collections.Generic; using Quadarax.Foundation.Core.Exceptions; using System.Linq; using Quadarax.Foundation.Core.Value.Extensions; namespace Quadarax.Foundation.Core.Data { public class Result : IResult { #region *** Properties *** public bool IsSuccess { get; protected set; } public IEnumerable Errors => _errors; public static IResult Ok => new Result(); public static IResult Fail => new Result(false, new List { new Error("Operation failed", 0, ErrorLevelEnum.Error) }); #endregion #region *** Private Fields *** private readonly IList _errors = new List(); #endregion #region *** Constructors *** public Result() : this(true, null) { } public Result(IEnumerable errors) : this(false, errors) { } public Result(bool isSuccess, IEnumerable? errors) { errors ??= new List(); IsSuccess = isSuccess; _errors.AddRange(errors); } #endregion #region *** Operations *** public void SetSuccess(bool isSuccess) { IsSuccess = isSuccess; } public void AddError(IError error) { if (error == null) throw new ArgumentNullException(nameof(error)); _errors.Add(error); } public void ClearErrors() { _errors.Clear(); } public object? GetValue() { return null; } public void ThrowIfError() { if (IsSuccess) return; throw new AggregateException(Errors.Select(e => e.AsCodeException())); } public AggregateException? ToAggregateException() { if (IsSuccess) return null; var errors = new List(); foreach (var e in Errors) { errors.Add(e.AsCodeException()); } return new AggregateException(errors); } #endregion } }