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

namespace Intemi.InTrees.Implements
{
    public class NodePuritySC : IStoppingCriterion
    {
        private NaturalStoppingCriterium naturalSC = new NaturalStoppingCriterium();
        private double purityLimit;

        public NodePuritySC(double purityLimit)
        {
            this.purityLimit = purityLimit;
        }

        public bool Stop(IDataTable dataTable, ref bool shouldTerminate)
        {
            bool stop = naturalSC.Stop(dataTable, ref shouldTerminate);
            if (!stop)
                stop = (NodePurity(dataTable) >= purityLimit);
            return (stop);
        }

        public bool Stop(IDataTable dataTable, List<INodeTest> nodeTests, ref bool shouldTerminate)
        {
            bool stop = naturalSC.Stop(dataTable,nodeTests, ref shouldTerminate);
            if (!stop)
                stop = (NodePurity(dataTable) >= purityLimit);
            return (stop);
        }


        private double NodePurity(IDataTable dataTable)
        {
            double purity = 1;
            if (dataTable.InstanceCount > 0)
            {
                IOneFeatureData tt = (dataTable as ITargets).Targets;
                int[] counts = tt.FeatureStatistics.counts;
                int maxi = 0;
                for (int i = 0; i < counts.Length; i++)
                {
                    if (counts[i] > counts[maxi])
                    {
                        maxi = i;
                    }
                }
                purity = (double)counts[maxi] / dataTable.InstanceCount;
            }
            return (purity);
        }

    }
}
