﻿using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.Common;

namespace QuickRecon
{
    public class Reconcilation
    {
        public static void Reconcile()
        {
            string sourceFile = ConfigSettings.SourceFile;
            string targetFile = ConfigSettings.TargetFile;
            string appName = ConfigSettings.DbConnectionString;

            var sourceDataTable = sourceFile.ReadCsvFile(ConfigSettings.SourceTable);
            var targetDataTable = targetFile.ReadCsvFile(ConfigSettings.TargetTable);

            DbConnection connection = appName.GetConnection();

            var sourceTableQueryText = sourceDataTable.GetCreateTableQuery();
            var targetTableQueryText = targetDataTable.GetCreateTableQuery();

            sourceTableQueryText.ExecuteSql(connection);
            targetTableQueryText.ExecuteSql(connection);

            DbHelper.InsertData(appName, connection, sourceDataTable);
            DbHelper.InsertData(appName, connection, targetDataTable);

            var resultTableQueryText = sourceDataTable.GetCreateTableQuery(ConfigSettings.ResultTable);

            resultTableQueryText.ExecuteSql(connection);
            ConfigSettings.SqlQuery.AlterResultTableDefn.ExecuteSql(connection);

            var reconcilationQueryDetails = ReconcilationHelper.GetReconcilationQueryDetails(sourceDataTable, targetDataTable, connection);
            ExecuteReconcilationSteps(reconcilationQueryDetails);

            connection.Close();
        }

        static void ExecuteReconcilationSteps(List<QueryDetails> queries)
        {    
            queries.ForEach(query => query.Table
                                            .GetColumnNames()
                                            .GetQueryText(query.QueryType, query.TableAliasName)
                                            .ExecuteSql(query.DbConnection));
        }
    }
}