using dataladder.Data;
using dataladder.Matching;
using System;

namespace DataMatching.Matching
{
    public class MatchManager
    {
        private MatchSettings _matchSettings;

        public MatchManager(MatchSettings matchSettings)
        {
            _matchSettings = matchSettings;    
        }

        private MatchSettings Settings => _matchSettings;

        public void FindMatches()
        {
            MatchEngine matchEngine = new MatchEngine(Settings.MatchDefinitionManager, Settings.AllRecordsInGoupMustBeSimilar, 
                Settings.TempPath, Settings.DataPath, Settings.Name);

            matchEngine.InputDataMapperDict.Clear();

            foreach (var table in Settings.Tables)
            {
                OnDriveTable sourceTable = table as OnDriveTable;

                if (sourceTable != null)
                {
                    sourceTable.PriorityForMemory = OnDriveTable.PrioritiesForMemory.Normal;
                }
                
                matchEngine.InputDataMapperDict.Add(table.Name, table);
            }

            matchEngine.DataSourceIndexPairList.Clear();
            Settings.SourcePairs?.ForEach(p => matchEngine.DataSourceIndexPairList.Add(p));                     

            matchEngine.DoIndex();
            matchEngine.DoMatch(Settings.MaxMatchesForOneRow, Settings.ClearAllAfterMatching, Settings.MaxMatchesPerGroup);
            matchEngine.ProcessFinalResults();

            String dataPath = matchEngine.DataPath;

            String pairsFileNameBase = matchEngine.PairsScoresTable.FileNameBase;
            String groupsFileNameBase = matchEngine.FinalScoresGroupsTable.FileNameBase;

            //String pairsFilePath = matchEngine.PairsScoresTable.FilesPath;
            //String groupsFilePath = matchEngine.FinalScoresGroupsTable.FilesPath;

            matchEngine.Dispose();

            Settings.PairsScoresTable = new OnDriveTable(dataPath, pairsFileNameBase);
            Settings.FinalScoresGroupsTable = new OnDriveTable(dataPath, groupsFileNameBase);

        }
    }
}
