using System;
using System.Collections.Generic;
namespace Csla.Validation
{
  /// 
  /// Maintains rule methods for a business object
  /// or business object type.
  /// 
  internal class ValidationRulesManager
  {
    private Dictionary _rulesList;
    internal Dictionary RulesDictionary
    {
      get
      {
        if (_rulesList == null)
          _rulesList = new Dictionary();
        return _rulesList;
      }
    }
    internal RulesList GetRulesForProperty(
      string propertyName,
      bool createList)
    {
      // get the list (if any) from the dictionary
      RulesList list = null;
      if (RulesDictionary.ContainsKey(propertyName))
        list = RulesDictionary[propertyName];
      if (createList && list == null)
      {
        // there is no list for this name - create one
        list = new RulesList();
        RulesDictionary.Add(propertyName, list);
      }
      return list;
    }
    #region Adding Rules
    public void AddRule(RuleHandler handler, RuleArgs args, int priority)
    {
      // get the list of rules for the property
      List list = GetRulesForProperty(args.PropertyName, true).GetList(false);
      // we have the list, add out new rule
      list.Add(new RuleMethod(handler, args, priority));
    }
    public void AddRule(RuleHandler handler, R args, int priority) where R : RuleArgs
    {
      // get the list of rules for the property
      List list = GetRulesForProperty(args.PropertyName, true).GetList(false);
      // we have the list, add out new rule
      list.Add(new RuleMethod(handler, args, priority));
    }
    #endregion
    #region Adding Dependencies
    /// 
    /// Adds a property to the list of dependencies for
    /// the specified property
    /// 
    /// 
    /// The name of the property.
    /// 
    /// 
    /// The name of the dependant property.
    /// 
    /// 
    /// When rules are checked for propertyName, they will
    /// also be checked for any dependant properties associated
    /// with that property.
    /// 
    public void AddDependantProperty(string propertyName, string dependantPropertyName)
    {
      // get the list of rules for the property
      List list = GetRulesForProperty(propertyName, true).GetDependancyList(true);
      // we have the list, add the dependency
      list.Add(dependantPropertyName);
    }
    #endregion
  }
}