/// <summary>
        /// Returns nodes by rules.
        /// </summary>
        /// <typeparam name="TFactRule">FatcRule type.</typeparam>
        /// <typeparam name="TWantAction">WantAction type.</typeparam>
        /// <typeparam name="TFactContainer">FactContainer type.</typeparam>
        /// <param name="rules">List of rule.</param>
        /// <param name="treeByFactRule">Rule tree.</param>
        /// <param name="parentNode">Parent node.</param>
        /// <returns>Node list.</returns>
        public static List <NodeByFactRule <TFactRule> > GetNodesByRules <TFactRule, TWantAction, TFactContainer>(this IEnumerable <TFactRule> rules, NodeByFactRule <TFactRule> parentNode, TreeByFactRule <TFactRule, TWantAction, TFactContainer> treeByFactRule)
            where TFactRule : IFactRule
            where TWantAction : IWantAction
            where TFactContainer : IFactContainer
        {
            var context = treeByFactRule.Context;
            var result  = new List <NodeByFactRule <TFactRule> >();

            foreach (var rule in rules)
            {
                NodeByFactRuleInfo <TFactRule> nodeInfo = treeByFactRule.NodeInfos.FirstOrDefault(nInfo => nInfo.Rule.EqualsWork(rule, context.WantAction, context.Container));

                if (nodeInfo == null)
                {
                    nodeInfo = new NodeByFactRuleInfo <TFactRule>
                    {
                        Rule = rule,
                        BuildSuccessConditions = new List <IBuildConditionFact>(rule.InputFactTypes.Count(type => type.IsFactType <IBuildConditionFact>())),
                        BuildFailedConditions  = new List <IBuildConditionFact>(),
                        RuntimeConditions      = new List <IRuntimeConditionFact>(rule.InputFactTypes.Count(type => type.IsFactType <IRuntimeConditionFact>())),
                        RequiredFactTypes      = context.SingleEntity.GetRequiredTypesOfFacts(rule, context).ToList(),
                        CompatibleRules        = rule.GetCompatibleRulesEx(context.FactRules, context),
                    }
                }
                ;

                result.Add(new NodeByFactRule <TFactRule>
                {
                    Childs = new List <NodeByFactRule <TFactRule> >(),
                    Info   = nodeInfo,
                    Parent = parentNode,
                });
            }

            return(result);
        }
 public void Initialize()
 {
     Rule     = GetFactRule((Priority1 p, Fact1 f) => new FactResult(f.Value + p));
     NodeInfo = new NodeByFactRuleInfo <FactRule>
     {
         BuildFailedConditions = new List <IBuildConditionFact>(),
         Rule = Rule,
         BuildSuccessConditions = new List <IBuildConditionFact>(),
         RuntimeConditions      = new List <IRuntimeConditionFact>(),
     };
     Node = new NodeByFactRule <FactRule>
     {
         Childs = new List <NodeByFactRule <FactRule> >(),
         Info   = NodeInfo,
         Parent = null,
     };
     Context = GetWantActionContext(
         GetWantAction((FactResult result) => { }),
         new FactContainer
     {
         new Priority1(),
         new Priority2(),
     });
 }
        /// <inheritdoc/>
        public virtual bool TryBuildTreeForFactInfo <TFactRule, TWantAction, TFactContainer>(BuildTreeForFactInfoRequest <TFactRule, TWantAction, TFactContainer> request, out TreeByFactRule <TFactRule, TWantAction, TFactContainer> treeResult, out List <DeriveFactErrorDetail> deriveFactErrorDetails)
            where TFactRule : IFactRule
            where TWantAction : IWantAction
            where TFactContainer : IFactContainer
        {
            var context = request.Context;

            treeResult             = null;
            deriveFactErrorDetails = null;

            // find the rules that can calculate the fact
            List <TreeByFactRule <TFactRule, TWantAction, TFactContainer> > treesByWantFactType = request.GetTreesByRequest();
            var treeReady = treesByWantFactType.FirstOrDefault(tree => tree.Status == TreeStatus.Built);

            if (treeReady != null)
            {
                treeResult = treeReady;
                return(true);
            }

            List <List <IFactType> > notFoundFactSet = treesByWantFactType.ConvertAll(item => new List <IFactType>());
            var allFinichedNodes = new Dictionary <NodeByFactRuleInfo <TFactRule>, NodeByFactRule <TFactRule> >();

            while (true)
            {
                for (int i = treesByWantFactType.Count - 1; i >= 0; i--)
                {
                    var treeByWantFactType = treesByWantFactType[i];

                    if (treeByWantFactType.Status != TreeStatus.BeingBuilt)
                    {
                        continue;
                    }

                    int lastlevelNumber = treeByWantFactType.Levels.Count - 1;

                    // If after synchronization we can calculate the tree.
                    if (TrySyncTreeLevelsAndFinishedNodes(treeByWantFactType, lastlevelNumber, allFinichedNodes))
                    {
                        treeByWantFactType.Built();
                        continue;
                    }

                    List <NodeByFactRule <TFactRule> > lastTreeLevel = treeByWantFactType.Levels[lastlevelNumber];

                    // If in the last level there are no nodes for calculation, then the tree can be calculated.
                    if (lastTreeLevel.Count == 0)
                    {
                        treeByWantFactType.Built();
                        continue;
                    }

                    // Next level nodes.
                    var  nextTreeLevel             = new List <NodeByFactRule <TFactRule> >();
                    var  currentLevelFinishedNodes = new Dictionary <NodeByFactRuleInfo <TFactRule>, NodeByFactRule <TFactRule> >();
                    bool cannotDerived             = false;

                    for (int j = 0; j < lastTreeLevel.Count; j++)
                    {
                        NodeByFactRule <TFactRule>     node     = lastTreeLevel[j];
                        NodeByFactRuleInfo <TFactRule> nodeInfo = node.Info;
                        Dictionary <NodeByFactRuleInfo <TFactRule>, NodeByFactRule <TFactRule> > copatibleAllFinishedNodes = nodeInfo.GetCompatibleFinishedNodes(allFinichedNodes, context);
                        List <IFactType> needFacts = nodeInfo
                                                     .RequiredFactTypes
                                                     .FindAll(needFactType => !CanRemoveFromNeedFactTypes(needFactType, node, context, copatibleAllFinishedNodes));

                        // If the rule can be calculated from the parameters in the container, then add the node to the list of complete.
                        if (needFacts.IsNullOrEmpty())
                        {
                            allFinichedNodes.Add(node.Info, node);
                            currentLevelFinishedNodes.Add(node.Info, node);
                            continue;
                        }

                        bool canTryRemoveNode = false;
                        foreach (var needFact in needFacts)
                        {
                            if (needFact.IsFactType <ISpecialFact>())
                            {
                                if (!canTryRemoveNode)
                                {
                                    canTryRemoveNode = true;
                                }

                                notFoundFactSet[i].Add(needFact);
                                continue;
                            }

                            var needRules = nodeInfo
                                            .CompatibleRules
                                            .FindAll(rule => rule.OutputFactType.EqualsFactType(needFact) && !rule.RuleContainBranch(node));

                            if (needRules.Count > 0)
                            {
                                List <NodeByFactRule <TFactRule> > nodes = needRules.GetNodesByRules(node, treeByWantFactType);
                                nextTreeLevel.AddRange(nodes);
                                node.Childs.AddRange(nodes);
                            }
                            else
                            {
                                if (!canTryRemoveNode)
                                {
                                    canTryRemoveNode = true;
                                }

                                notFoundFactSet[i].Add(needFact);
                            }
                        }

                        if (canTryRemoveNode)
                        {
                            // Is there a neighboring node capable of deriving this fact.
                            cannotDerived = TryRemoveRootNode(node, treeByWantFactType, lastlevelNumber);
                            j--;
                        }
                    }

                    if (cannotDerived)
                    {
                        treeByWantFactType.Cencel();
                    }
                    else if (currentLevelFinishedNodes.Count > 0)
                    {
                        if (TrySyncTreeLevelsAndFinishedNodes(treeByWantFactType, lastlevelNumber, currentLevelFinishedNodes))
                        {
                            treeByWantFactType.Built();
                        }
                        else if (nextTreeLevel.Count > 0)
                        {
                            SyncTreeLevelAndFinishedNodes(nextTreeLevel, currentLevelFinishedNodes, context);
                            treeByWantFactType.Levels.Add(nextTreeLevel);
                        }
                    }
                    else if (nextTreeLevel.Count > 0)
                    {
                        treeByWantFactType.Levels.Add(nextTreeLevel);
                    }
                    else
                    {
                        treeByWantFactType.Built();
                    }
                }

                List <TreeByFactRule <TFactRule, TWantAction, TFactContainer> > builtTrees = treesByWantFactType
                                                                                             .FindAll(tree => tree.Status == TreeStatus.Built);

                if (builtTrees.Count != 0)
                {
                    var countRuleByBuiltTrees = builtTrees.ToDictionary(tree => tree, tree => tree.GetUniqueRulesFromTree().Count);
                    int minRuleCount          = countRuleByBuiltTrees.Min(item => item.Value);
                    var suitableTree          = countRuleByBuiltTrees.First(item => item.Value == minRuleCount).Key;

                    foreach (var tree in treesByWantFactType)
                    {
                        if (tree != suitableTree && tree.Status != TreeStatus.Cencel && tree.GetUniqueRulesFromTree().Count >= minRuleCount)
                        {
                            tree.Cencel();
                        }
                    }

                    if (treesByWantFactType.All(tree => tree.Status != TreeStatus.BeingBuilt))
                    {
                        treeResult = suitableTree;
                        return(true);
                    }
                }

                if (treesByWantFactType.All(tree => tree.Status == TreeStatus.Cencel))
                {
                    break;
                }
            }

            deriveFactErrorDetails = new List <DeriveFactErrorDetail>();

            foreach (var factSet in notFoundFactSet)
            {
                if (factSet.Count != 0)
                {
                    deriveFactErrorDetails.Add(new DeriveFactErrorDetail(request.WantFactType, factSet.AsReadOnly()));
                }
            }

            return(false);
        }
 internal static Dictionary <NodeByFactRuleInfo <TFactRule>, NodeByFactRule <TFactRule> > GetCompatibleFinishedNodes <TFactRule, TWantAction, TFactContainer>(this NodeByFactRuleInfo <TFactRule> nodeInfo, Dictionary <NodeByFactRuleInfo <TFactRule>, NodeByFactRule <TFactRule> > finishedNodes, IWantActionContext <TWantAction, TFactContainer> context)
     where TFactRule : IFactRule
     where TWantAction : IWantAction
     where TFactContainer : IFactContainer
 {
     return(finishedNodes
            .Where(finishedNode => context.SingleEntity.CompatibleRule(nodeInfo.Rule, finishedNode.Key.Rule, context))
            .ToDictionary(finishedNode => finishedNode.Key, finishedNode => finishedNode.Value));
 }