using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AyaNova.Biz
{

    /// <summary>
    /// Business object base class
    /// </summary>
    internal abstract class BizObject : IBizObject
    {

        public BizObject()
        {

        }





        #region common props

        internal AyaType BizType { get; set; }
        internal AyaNova.Models.AyContext ct { get; set; }
        internal long UserId { get; set; }
        internal long UserTranslationId { get; set; }
        internal AuthorizationRoles CurrentUserRoles { get; set; }

        #endregion



        #region Error handling
        private readonly List<ValidationError> _errors = new List<ValidationError>();



        public List<ValidationError> Errors => _errors;

        public bool HasErrors => _errors.Any();

        public void ClearErrors() => _errors.Clear();

        public void AddvalidationError(ValidationError validationError)
        {
            _errors.Add(validationError);
        }

        public bool PropertyHasErrors(string propertyName)
        {
            if (_errors.Count == 0) return false;
            var v = _errors.FirstOrDefault(m => m.Target == propertyName);
            return (v != null);

        }

        public void AddError(ApiErrorCode errorCode, string propertyName = null, string errorMessage = null)
        {

            _errors.Add(new ValidationError() { Code = errorCode, Message = errorMessage, Target = propertyName });
        }

        public string GetErrorsAsString()
        {
            if (!HasErrors) return string.Empty;

            StringBuilder sb = new StringBuilder();
            sb.AppendLine("Validation errors:");
            foreach (ValidationError e in _errors)
            {
                var msg = e.Message;
                if (string.IsNullOrWhiteSpace(msg))
                {
                    //msg = e.ErrorType.ToString();
                    msg = ApiErrorCodeStockMessage.GetMessage(e.Code);
                }
                sb.AppendLine($"Target: {e.Target} error: {msg}");
            }
            return sb.ToString();
        }


        #endregion error handling

    }//eoc

}//eons