//
// DatabaseConfiguration.cs
//
// Author:
//       Carsten Sonne Larsen <cs@innolan.dk>
//
// Copyright (c) 2013-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 System.Collections.Generic;
using Ntp.Analyzer.Localize;
using Ntp.Config;

namespace Ntp.Data
{
    public sealed class DatabaseConfiguration : ConfigurationBase
    {
        private DatabaseConfiguration(
            string configName,
            int indentLevel,
            SqlDatabaseProvider provider,
            string host,
            int port,
            string name,
            string user,
            string pass,
            bool initialize,
            bool upgrade
            )
            : base(configName, indentLevel)
        {
            this.host = host;
            this.provider = provider;
            this.port = port != 0 ? port : (int?) null;
            this.name = name;
            this.user = user;
            this.pass = pass;
            this.initialize = initialize;
            this.upgrade = upgrade;
        }

        public const string Identifier = ConfigurationKeyword.Database;

        private const bool InitializeDefault = false;
        private const bool UpgradeDefault = false;

        private static readonly String[] Params =
        {
            ConfigurationKeyword.Database,
            ConfigurationKeyword.DatabaseProvider,
            ConfigurationKeyword.DatabaseHost,
            ConfigurationKeyword.DatabasePort,
            ConfigurationKeyword.DatabaseName,
            ConfigurationKeyword.DatabaseUser,
            ConfigurationKeyword.DatabasePass,
            ConfigurationKeyword.DatabaseCreate,
            ConfigurationKeyword.DatabaseUpgrade
        };

        private readonly string host;
        private readonly bool initialize;
        private readonly bool upgrade;
        private readonly string name;
        private readonly string pass;
        private readonly int? port;
        private readonly SqlDatabaseProvider provider;
        private readonly string user;

        protected override IEnumerable<Object> Items
        {
            get
            {
                var items = new List<object> {ConfigName, GetProviderString(), host};

                if (port.HasValue)
                    items.Add(port.Value);

                items.Add(name);
                items.Add(user);
                items.Add(pass);

                if (!ShowDefault && initialize != InitializeDefault)
                    items.Add(initialize);

                if (!ShowDefault && upgrade != UpgradeDefault)
                    items.Add(upgrade);

                return items.ToArray();
            }
        }

        public string Host
        {
            get { return host; }
        }

        public int? Port
        {
            get { return port; }
        }

        public string Name
        {
            get { return name; }
        }

        public string User
        {
            get { return user; }
        }

        public string Pass
        {
            get { return pass; }
        }

        public bool Initialize
        {
            get { return initialize; }
        }

        public bool Upgrade
        {
            get { return upgrade; }
        }

        public SqlDatabaseProvider Provider
        {
            get { return provider; }
        }

        private string GetProviderString()
        {
            switch (provider)
            {
                case SqlDatabaseProvider.MySql:
                    return ConfigurationKeyword.DatabaseProviderMySql;
                case SqlDatabaseProvider.PostgreSql:
                    return ConfigurationKeyword.DatabaseProviderPostgre;
                default:
                    return ConfigurationKeyword.TypeUnknown;
            }
        }

        public override string ToString()
        {
            var list = new List<String>
            {
                ConfigurationKeyword.Database,
                ConfigurationKeyword.DatabaseProvider,
                ConfigurationKeyword.DatabaseHost
            };

            if (port.HasValue)
                list.Add(ConfigurationKeyword.DatabasePort);

            list.Add(ConfigurationKeyword.DatabaseName);
            list.Add(ConfigurationKeyword.DatabaseUser);
            list.Add(ConfigurationKeyword.DatabasePass);

            if (!ShowDefault && initialize != InitializeDefault)
                list.Add(ConfigurationKeyword.DatabaseCreate);

            if (!ShowDefault && upgrade != UpgradeDefault)
                list.Add(ConfigurationKeyword.DatabaseUpgrade);
            
            return ConfigText(list.ToArray(), Items);
        }

        private static SqlDatabaseProvider GetSqlDatabaseProviderString(
            Dictionary<String, String> options,
            string type,
            string configPath)
        {
            if (!options.ContainsKey(type) || options[type].Trim() == String.Empty)
            {
                ConfigError(String.Format(ConfigurationMessage.NoValueForSetting, type, configPath));
                return SqlDatabaseProvider.Unknown;
            }

            string provider = options[type].Trim().ToLower();
            if (provider == ConfigurationKeyword.DatabaseProviderMySql.ToLower())
            {
                return SqlDatabaseProvider.MySql;
            }
            if (provider == ConfigurationKeyword.DatabaseProviderPostgre.ToLower())
            {
                return SqlDatabaseProvider.PostgreSql;
            }

            ConfigError(String.Format(ConfigurationMessage.InvalidValue, type, configPath));
            return SqlDatabaseProvider.Unknown;
        }

        public static DatabaseConfiguration Create(ConfigurationBlock config)
        {
            if (config == null)
                return null;

            Dictionary<String, String> options = GetOptions(Params, config);

            return new DatabaseConfiguration(
                GetOptionConfigName(options, Identifier, null, false, Identifier),
                config.IndentLevel,
                GetSqlDatabaseProviderString(options, ConfigurationKeyword.DatabaseProvider, Identifier),
                GetOptionString(options, ConfigurationKeyword.DatabaseHost, Identifier, true),
                GetOptionInteger(options, ConfigurationKeyword.DatabasePort, Identifier, false),
                GetOptionString(options, ConfigurationKeyword.DatabaseName, Identifier, true),
                GetOptionString(options, ConfigurationKeyword.DatabaseUser, Identifier, true),
                GetOptionString(options, ConfigurationKeyword.DatabasePass, Identifier, true),
                GetOptionBoolean(options, ConfigurationKeyword.DatabaseCreate, Identifier, false, InitializeDefault),
                GetOptionBoolean(options, ConfigurationKeyword.DatabaseUpgrade, Identifier, false, UpgradeDefault));
        }
    }
}