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

namespace Sockeye.Biz
{

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

        public BizObject()
        {

        }





        #region common props

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

        #endregion

        internal async Task<string> Translate(string key)
        {
            return await TranslationBiz.GetTranslationStaticAsync(key, UserTranslationId, ct);
        }

        #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 = "generalerror", string errorMessage = null)
        {
            //if Target is generalerror that means show in UI in general error box of form
            _errors.Add(new ValidationError() { Code = errorCode, Message = errorMessage, Target = propertyName });
        }


//TODO: CHILD COLLECTION MOD add error version for indexed child

        // //Add a bunch of errors, generally from a child object failed operastion
        // public void AddErrors(List<ValidationError> errors)
        // {
        //     _errors.AddRange(errors);
        // }

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

            StringBuilder sb = new StringBuilder();
            //  sb.AppendLine("LT:Errors - ");
            foreach (ValidationError e in _errors)
            {
                var msg = $"LT:{ApiErrorCodeStockMessage.GetTranslationCodeForApiErrorCode(e.Code)}";
                if (!string.IsNullOrWhiteSpace(e.Message))
                    msg += $", {e.Message}";
                if (!string.IsNullOrWhiteSpace(e.Target) && e.Target != "generalerror")
                    msg += $", field: {e.Target}";
                sb.AppendLine(msg);
            }
            return sb.ToString();
        }


        #endregion error handling

    }//eoc

}//eons