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

namespace BaseDomain.Base
{
    public abstract class AEntity<T, TKey> where TKey : class
                                  where T : class
    {
        ObjectValidatorBuilder<T> objectValidatorBuilder;
        bool rulesAdded;

        public ObjectValidatorBuilder<T> ValidatorBuilder { get { return objectValidatorBuilder; } }

        public AEntity()
        {
            T entity;
            try
            {
                entity = (T)Convert.ChangeType(this, typeof(T));
            }
            catch (InvalidCastException)
            {
                entity = default;
            }

            objectValidatorBuilder = new ObjectValidatorBuilder<T>(entity);
            AddRules();
        }

        public ObjectValidatorBuilder<T> InitValidator()
        {
            T entity;
            try
            {
                entity = (T)Convert.ChangeType(this, typeof(T));
            }
            catch (InvalidCastException)
            {
                entity = default;
            }

            objectValidatorBuilder = new ObjectValidatorBuilder<T>(entity);
            return objectValidatorBuilder;
        }

        public abstract TKey Id { get; set; }

        public void ValidateAndThrow()
        {
            SetClearAndRules();
            objectValidatorBuilder.ThrowErrorMessages();
        }

        public string GetErrorMessages()
        {
            SetClearAndRules();
            return objectValidatorBuilder.ErrorMessagesAsString();
        }

        public bool IsValid()
        {
            SetClearAndRules();
            return objectValidatorBuilder.IsValid();
        }

        private void SetClearAndRules()
        {
            objectValidatorBuilder.ClearRules();
            AddRules();
            objectValidatorBuilder.Build();
        }
        public abstract void AddRules();
    }
}
