using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using DigitalData.Modules.Database;
using DigitalData.Modules.Interfaces;
using Microsoft.Extensions.Configuration;

namespace ZUGFeRDRESTService
{
    public class Database: IDatabase
    {
        private string _gdPictureKey = null;
        private Dictionary<String, XmlItemProperty> _propertyMap = null;

        private const string QUERY_GET_GDPICTURE_KEY = "SELECT LICENSE FROM TBDD_3RD_PARTY_MODULES WHERE NAME = 'GDPICTURE'";
        private const string QUERY_GET_PROPERTY_MAP = "SELECT * FROM TBEDM_XML_ITEMS WHERE SPECIFICATION = '{0}' AND ACTIVE = True ORDER BY XML_PATH";

        public MSSQLServer MSSQL { get; set; }
        public Firebird Firebird { get; set; }

        public Database(ILogging Logging, IConfiguration Config)
        {
            var LogConfig = Logging.LogConfig;
            var Logger = Logging.LogConfig.GetLogger();
            var AppConfig = Config.GetSection("Config");
            var FBConfig = AppConfig.GetSection("Firebird");

            MSSQL = new MSSQLServer(LogConfig, AppConfig["MSSQLConnectionString"]);
            Firebird = new Firebird(LogConfig, FBConfig["Datasource"], FBConfig["Database"], FBConfig["Username"], FBConfig["Password"]);

            Logger.Debug("MSSQL Connection: [{0}]", MSSQL.CurrentSQLConnectionString);
            Logger.Debug("Firebird Connection: [{0}]", Firebird.ConnectionString);
        }

        public string GetGDPictureKey()
        {
            if (_gdPictureKey == null)
                _gdPictureKey = MSSQL.GetScalarValue(QUERY_GET_GDPICTURE_KEY).ToString();

            return _gdPictureKey;
        }

        public Dictionary<String, XmlItemProperty> GetPropertyMap()
        {
            if (_propertyMap == null)
            {
                _propertyMap = new Dictionary<string, XmlItemProperty>();
                var oDatatable = Firebird.GetDatatable(string.Format(QUERY_GET_PROPERTY_MAP, "DEFAULT"));

                foreach (DataRow oRow in oDatatable.Rows)
                {                
                    _propertyMap.Add(oRow["XML_PATH"].ToString(), new XmlItemProperty()
                    { 
                        Description = oRow["DESCRIPTION"].ToString(),
                        TableName = oRow["TABLE_NAME"].ToString(),
                        TableColumn = oRow["TABLE_COLUMN"].ToString(),
                        GroupScope = oRow["GROUP_SCOPE"].ToString(),
                        IsRequired = (bool)oRow["IS_REQUIRED"],
                        IsGrouped = (bool)oRow["IS_GROUPED"]
                    });
                }
            }             

            return _propertyMap;
        }
    }
}
