using System;
using System.Collections.Generic;
using System.Text;
using MySql.Data.MySqlClient;
using MarketData.MarketDataModel;
using MarketData.Utils;

namespace MarketData.DataAccess
{
  public class CurrencyConversionDA
  {
    private CurrencyConversionDA()
    {
    }
// get the maximum date on record on or before asof.  If maxDate turns out to be less than asof then return null
    public static DateTime? GetMaxDateForCurrency(String sourceCurrency,String destinationCurrency,DateTime asof)
    {
      MySqlConnection sqlConnection = null;
      MySqlDataReader sqlDataReader = null;
			MySqlCommand sqlCommand=null;
      String strQuery = null;
      DateTime? maxDate=null;

      try
      {
        StringBuilder sb = new StringBuilder();
        sqlConnection = SqlUtils.CreateMySqlConnection(MainDataSource.Instance.LocateDataSource("market_data"));
        sb.Append("select asof from CurrencyConversion ");
        sb.Append(" where ");
        sb.Append("source_currency=").Append("'").Append(sourceCurrency).Append("'").Append(" ");
        sb.Append("and ").Append(" destination_currency=").Append("'").Append(destinationCurrency).Append("'").Append(" ");
        sb.Append("and asof<=").Append("'").Append(Utility.DateTimeToStringYYYYHMMHDD(asof)).Append("'");
        sb.Append(" order by asof desc ");
        sb.Append(" limit 1");
        strQuery = sb.ToString(); ;
        sqlCommand = new MySqlCommand(strQuery, sqlConnection);
        sqlCommand.CommandTimeout = SqlUtils.COMMAND_TIMEOUT;
        sqlDataReader = sqlCommand.ExecuteReader();
        if (!sqlDataReader.Read()) return maxDate;
        if(!sqlDataReader.IsDBNull(0))maxDate=sqlDataReader.GetDateTime(0);
        if(maxDate<asof)return null;
        return maxDate;
      }
      catch (Exception exception)
      {
        MDTrace.WriteLine(LogLevel.DEBUG,exception);
        return null;
      }
      finally
      {
				if(null!=sqlCommand)sqlCommand.Dispose();
        if (null != sqlDataReader) sqlDataReader.Close();
        if (null != sqlConnection) sqlConnection.Close();
      }
    }
//  Assumes like source_currency and like asof
    public static bool InsertCurrencyConversionRates(CurrencyConversionCollection currencyConversionCollection)
    {
      MySqlConnection sqlConnection=null;
      MySqlTransaction sqlTransaction=null;
      try
      {
        if(null==currencyConversionCollection||0==currencyConversionCollection.Count)return false;
        sqlConnection = SqlUtils.CreateMySqlConnection(MainDataSource.Instance.LocateDataSource("market_data"));
        sqlTransaction = sqlConnection.BeginTransaction(System.Data.IsolationLevel.ReadCommitted);
        CurrencyConversionElement currencyConversionElementPrimary=currencyConversionCollection[0];
        RemoveCurrecyConversionForSourceAndDate(currencyConversionElementPrimary.SourceCurrency,currencyConversionElementPrimary.AsOf,sqlConnection,sqlTransaction);
        foreach(CurrencyConversionElement currencyConversionElement in currencyConversionCollection)
        {
          StringBuilder sb = new StringBuilder();
          sb.Append("insert into CurrencyConversion(asof,source_currency,destination_currency,destination_currency_name,units_per_source,source_per_unit) ");
          sb.Append("values(");
          sb.Append("'").Append(Utility.DateTimeToStringYYYYHMMHDD(currencyConversionElement.AsOf)).Append("'").Append(",");
          sb.Append("'").Append(currencyConversionElement.SourceCurrency).Append("'").Append(",");
          sb.Append("'").Append(currencyConversionElement.DestinationCurrency).Append("'").Append(",");
          sb.Append("'").Append(currencyConversionElement.DestinationCurrencyName).Append("'").Append(",");
          sb.Append(currencyConversionElement.UnitsPerSource).Append(",");
          sb.Append(currencyConversionElement.SourcePerUnit);
          sb.Append(")");
          String strQuery=sb.ToString();
          MySqlCommand sqlCommand = new MySqlCommand(strQuery, sqlConnection, sqlTransaction);
          sqlCommand.CommandTimeout = SqlUtils.COMMAND_TIMEOUT;
          sqlCommand.ExecuteNonQuery();
				  sqlCommand.Dispose();
        }
        sqlTransaction.Commit();
        return true;
      }
      catch(Exception exception)
      {
        MDTrace.WriteLine(LogLevel.DEBUG,exception);
        return false;
      }
      finally
      {
				if(null!=sqlTransaction)sqlTransaction.Dispose();
        if (null != sqlConnection) sqlConnection.Close();
      }
    }
    public static bool RemoveCurrecyConversionForSourceAndDate(String sourceCurrency,DateTime asof,MySqlConnection sqlConnection,MySqlTransaction sqlTransaction)
    {
      StringBuilder sb = new StringBuilder();
      String strQuery = null;

      try
      {
        sb.Append("delete from currencyconversion where ");
        sb.Append("source_currency='").Append(sourceCurrency).Append("'");
        sb.Append(" and ");
        sb.Append("asof='").Append(Utility.DateTimeToStringYYYYHMMHDD(asof)).Append("'");
        strQuery = sb.ToString();
        MySqlCommand sqlCommand = new MySqlCommand(strQuery, sqlConnection, sqlTransaction);
        sqlCommand.CommandTimeout = SqlUtils.COMMAND_TIMEOUT;
        sqlCommand.ExecuteNonQuery();
				sqlCommand.Dispose();
        return true;
      }
      catch (Exception exception)
      {
        sqlTransaction.Rollback();
        MDTrace.WriteLine(LogLevel.DEBUG,exception);
        if (null != strQuery) MDTrace.WriteLine(LogLevel.DEBUG,"Query was " + strQuery);
        return false;
      }
      finally
      {
      }
    }
    public static CurrencyConversionElement GetCurrencyConversionMaxDate(String sourceCurrency,String destinationCurrency, DateTime asof)
    {
      MySqlConnection sqlConnection = null;
      MySqlDataReader sqlDataReader = null;
			MySqlCommand sqlCommand=null;
      String strQuery = null;

      try
      {
        DateTime? maxDate=GetMaxDateForCurrency(sourceCurrency,destinationCurrency,asof);   // get the maximum date on record on or before max date
        if(null==maxDate)return null;
        StringBuilder sb = new StringBuilder();
        sqlConnection = SqlUtils.CreateMySqlConnection(MainDataSource.Instance.LocateDataSource("market_data"));
        sb.Append("select asof,source_currency,destination_currency,destination_currency_name,units_per_source,source_per_unit from CurrencyConversion where source_currency=");
        sb.Append("'").Append(sourceCurrency).Append("'").Append(" ");
        sb.Append(" and destination_currency=").Append("'").Append(destinationCurrency).Append("'").Append(" ");
        sb.Append("and asof=").Append("'").Append(Utility.DateTimeToStringYYYYHMMHDD(maxDate.Value)).Append("'");
        sb.Append(" limit 1");
        strQuery = sb.ToString(); ;
        sqlCommand = new MySqlCommand(strQuery, sqlConnection);
        sqlCommand.CommandTimeout = SqlUtils.COMMAND_TIMEOUT;
        sqlDataReader = sqlCommand.ExecuteReader();
        if (!sqlDataReader.Read()) return null;
        CurrencyConversionElement currencyConversionElement = new CurrencyConversionElement();
        currencyConversionElement.AsOf = sqlDataReader.GetDateTime(0);
        currencyConversionElement.SourceCurrency = sqlDataReader.GetString(1);
        currencyConversionElement.DestinationCurrency = sqlDataReader.GetString(2);
        if (!sqlDataReader.IsDBNull(2)) currencyConversionElement.DestinationCurrencyName = sqlDataReader.GetString(3);
        currencyConversionElement.UnitsPerSource = sqlDataReader.GetDouble(4);
        currencyConversionElement.SourcePerUnit = sqlDataReader.GetDouble(5);
        return currencyConversionElement;
      }
      catch (Exception exception)
      {
        MDTrace.WriteLine(LogLevel.DEBUG,exception);
        return null;
      }
      finally
      {
				if(null!=sqlCommand)sqlCommand.Dispose();
        if (null != sqlDataReader) sqlDataReader.Close();
        if (null != sqlConnection) sqlConnection.Close();
      }
    }
  }
}
