﻿namespace CC.Cumps.Configuration
{
    using System;
    using System.Collections.Generic;
    using System.Data.Common;
    using System.Data.SQLite;
    using System.IO;
    using Reporting.Infrastructure;
    using Reporting.Model;

    public class ReportingDatabaseBootstrapper
    {
        public const string DatabaseFile = "reportingDatabase.db3";
        
        private readonly List<Type> _dtos = new List<Type>
        {
            typeof(CustomerReport), 
            typeof(CustomerDetailsReport), 
        };

        private readonly SqlCreateBuilder _sqlCreateBuilder = new SqlCreateBuilder();

        public static void Bootstrap()
        {
            //new ReportingDatabaseBootstrapper().CreateDatabaseSchemaIfNeeded();
            new ReportingDatabaseBootstrapper().ReCreateDatabaseSchema();
        }

        public void ReCreateDatabaseSchema()
        {
            if (File.Exists(DatabaseFile))
                File.Delete(DatabaseFile);

            DoCreateDatabaseSchema();
        }

        public void CreateDatabaseSchemaIfNeeded()
        {
            if (File.Exists(DatabaseFile))
                return;

            DoCreateDatabaseSchema();
        }

        private void DoCreateDatabaseSchema()
        {
            SQLiteConnection.CreateFile(DatabaseFile);

            var sqLiteConnection = new SQLiteConnection(string.Format("Data Source={0}", DatabaseFile));

            sqLiteConnection.Open();

            using (DbTransaction dbTrans = sqLiteConnection.BeginTransaction())
            {
                using (DbCommand sqLiteCommand = sqLiteConnection.CreateCommand())
                {
                    foreach (var dto in _dtos)
                    {
                        sqLiteCommand.CommandText = _sqlCreateBuilder.CreateSqlCreateStatementFromDto(dto);
                        sqLiteCommand.ExecuteNonQuery();
                    }
                }
                dbTrans.Commit();
            }

            sqLiteConnection.Close();
        }
    }
}