//
// DataInitializer.cs
//
// Author:
//       Carsten Sonne Larsen <cs@innolan.dk>
//
// Copyright (c) 2016 Carsten Sonne Larsen
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using Ntp.Analyzer.Log;
using MySql.Data.MySqlClient;
using Ntp.Analyzer.Data.Static;
using System.Collections.Generic;
using Ntp.Analyzer.Data;
using System.Data;

namespace Ntp.Analyzer.Data
{
    public sealed class DataInitializer
    {
        public DataInitializer (LogBase log)
        {
            this.log = log;
        }

        private readonly LogBase log;

        public void CreateDatabase()
        {
            CreateDatabaseInternal ();
            CreateTables ();
        }

        private void CreateDatabaseInternal()
        {
            const string checkSql = "CREATE DATABASE IF NOT EXISTS {0};";
            string sql = String.Format (checkSql, DataConnection.DatabaseName);

            MySqlConnection connection = null;

            try {
                connection = new MySqlConnection (DataConnection.InitializeString);
                connection.Open ();

                MySqlCommand command = new MySqlCommand () {
                    Connection = connection,
                    CommandText = sql
                };

                command.Prepare ();
                command.ExecuteNonQuery ();
            } finally {
                if (connection != null && connection.State == ConnectionState.Open)
                    connection.Close ();
            }
        }

        private void CreateTables()
        {
            TimeServerDatabaseMapper timeServerMapper;
            PeerDatabaseMapper peerMapper;
            HostDatabaseMapper hostMapper;

            List<ITableInitializer> initializers = new List<ITableInitializer> ();
            initializers.Add (timeServerMapper = new TimeServerDatabaseMapper (log));
            initializers.Add (peerMapper = new PeerDatabaseMapper (timeServerMapper, log));
            initializers.Add (hostMapper = new HostDatabaseMapper (log));
            initializers.Add (new HostReadingDatabaseMapper (hostMapper, peerMapper, log));
            initializers.Add (new PeerReadingDatabaseMapper (hostMapper, peerMapper, log));
            initializers.Add (new HostIOReadingDatabaseMapper (hostMapper, log));

            foreach (ITableInitializer initializer in initializers) {
                try {
                    initializer.CheckTable();
                } catch (Exception e) {
                    log.WriteLine ("Could not create database table.", Severity.Error);
                    log.WriteLine (e, Severity.Trace);
                }
            }
        }
    }
}