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

namespace MarketData.DataAccess
{
  public class SplitsDA
  {
    private SplitsDA()
    {
    }
    public static bool InsertSplit(Split split)
    {
      Splits splits=new Splits();
      splits.Add(split);
      InsertSplits(splits);
      return true;
    }
    public static bool ContainsSplit(Split split)
    {
      MySqlConnection sqlConnection = null;
      MySqlDataReader sqlDataReader = null;
			MySqlCommand sqlCommand=null;
      String strQuery = null;
      int recordCount = 0;

      try
      {
        StringBuilder sb = new StringBuilder();
        sqlConnection = SqlUtils.CreateMySqlConnection(MainDataSource.Instance.LocateDataSource("market_data"));
        sb.Append("select count(*) from splits where symbol='").Append(split.Symbol).Append("' ");
        sb.Append("and effective_date='").Append(SqlUtils.SqlDate(split.EffectiveDate)).Append("' ");
        strQuery = sb.ToString();
        sqlCommand = new MySqlCommand(strQuery, sqlConnection);
        sqlCommand.CommandTimeout = SqlUtils.COMMAND_TIMEOUT;
        sqlDataReader = sqlCommand.ExecuteReader();
        if (sqlDataReader.Read())
        {
          if (!sqlDataReader.IsDBNull(0)) recordCount = sqlDataReader.GetInt32(0);
        }
				sqlCommand.Dispose();
        return 0 == recordCount ? false : true;
      }
      catch (Exception exception)
      {
        MDTrace.WriteLine(LogLevel.DEBUG,exception);
        return false;
      }
      finally
      {
				if(null!=sqlCommand)sqlCommand.Dispose();
        if (null != sqlDataReader) sqlDataReader.Close();
        if (null != sqlConnection) sqlConnection.Close();
      }
    }
    public static bool UpdateSplit(Split split)
    {
      MySqlConnection sqlConnection = null;
      MySqlTransaction sqlTransaction = null;
			MySqlCommand sqlCommand=null;
      String strQuery = null;

      try
      {
        if(!ContainsSplit(split))return false;
        sqlConnection = SqlUtils.CreateMySqlConnection(MainDataSource.Instance.LocateDataSource("market_data"));
        sqlTransaction = sqlConnection.BeginTransaction(System.Data.IsolationLevel.ReadCommitted);
        StringBuilder sb = new StringBuilder();
        DateTime modified=DateTime.Now;
        if(split.Applied&&(Utility.IsEpoch(split.AppliedLeastRecent)||Utility.IsEpoch(split.AppliedMostRecent)))
        {
          MDTrace.WriteLine(LogLevel.DEBUG,"Applied split requires AppliedRecent and AppliedMostRecent dates.");
          return false;
        }
        if(!split.Applied)return false;
        sb.Append("update splits set ");
        sb.Append("applied=").Append(split.Applied).Append(", ");
        sb.Append("applied_least_recent='").Append(SqlUtils.SqlDate(split.AppliedLeastRecent)).Append("'").Append(", ");
        sb.Append("applied_most_recent='").Append(SqlUtils.SqlDate(split.AppliedMostRecent)).Append("'").Append(", ");
        sb.Append("modified='").Append(SqlUtils.SqlDate(modified)).Append("'").Append(" ");
        sb.Append(" where symbol='").Append(split.Symbol).Append("'").Append(" and ");
        sb.Append("effective_date='").Append(SqlUtils.SqlDate(split.EffectiveDate)).Append("'");
        strQuery = sb.ToString();
        sqlCommand = new MySqlCommand(strQuery, sqlConnection, sqlTransaction);
        sqlCommand.CommandTimeout = SqlUtils.COMMAND_TIMEOUT;
        sqlCommand.ExecuteNonQuery();
        sqlTransaction.Commit();
        return true;
      }
      catch (Exception exception)
      {
        MDTrace.WriteLine(LogLevel.DEBUG,exception);
        MDTrace.WriteLine(LogLevel.DEBUG,"Query was '" + strQuery + "'");
        return false;
      }
      finally
      {
				if(null!=sqlCommand)sqlCommand.Dispose();
				if(null!=sqlTransaction)sqlTransaction.Dispose();
        if (null != sqlConnection) sqlConnection.Close();
      }
    }
    public static Splits GetUnappliedSplits()
    {
      MySqlConnection sqlConnection = null;
			MySqlCommand sqlCommand=null; 
      MySqlDataReader sqlDataReader=null;
      String strQuery = null;
      Splits splits=new Splits();                                

      try
      {
        sqlConnection = SqlUtils.CreateMySqlConnection(MainDataSource.Instance.LocateDataSource("market_data"));
        StringBuilder sb = new StringBuilder();
        DateTime modified=DateTime.Now;
        sb.Append("select symbol,effective_date,ratio,applied,applied_least_recent,applied_most_recent,modified,created from splits where Symbol in(select symbol from securitymaster) and applied=0 order by symbol,effective_date desc");
        strQuery = sb.ToString();
        sqlCommand = new MySqlCommand(strQuery, sqlConnection);
        sqlCommand.CommandTimeout = SqlUtils.COMMAND_TIMEOUT;
        sqlDataReader=sqlCommand.ExecuteReader();
        while(sqlDataReader.Read())
        {
          Split split=new Split();
          split.Symbol=sqlDataReader.GetString(0);
          split.EffectiveDate=sqlDataReader.GetDateTime(1);
          split.StrRatio=sqlDataReader.GetString(2);
          split.Applied=sqlDataReader.GetInt32(3)==0?false:true;
          if(!sqlDataReader.IsDBNull(4))split.AppliedLeastRecent=sqlDataReader.GetDateTime(4);
          if(!sqlDataReader.IsDBNull(5))split.AppliedMostRecent=sqlDataReader.GetDateTime(5);
          if(!sqlDataReader.IsDBNull(6))split.Modified=sqlDataReader.GetDateTime(6);
          if(!sqlDataReader.IsDBNull(7))split.Created=sqlDataReader.GetDateTime(7);
          splits.Add(split);
        }
        return splits;
      }
      catch (Exception exception)
      {
        MDTrace.WriteLine(LogLevel.DEBUG,exception);
        MDTrace.WriteLine(LogLevel.DEBUG,"Query was '" + strQuery + "'");
        return null;
      }
      finally
      {
				if(null!=sqlCommand)sqlCommand.Dispose();
        if (null != sqlConnection) sqlConnection.Close();
      }
    }
    public static Splits GetSplits(String symbol)
    {
      MySqlConnection sqlConnection = null;
			MySqlCommand sqlCommand=null; 
      MySqlDataReader sqlDataReader=null;
      String strQuery = null;
      Splits splits=new Splits();                                

      try
      {
        sqlConnection = SqlUtils.CreateMySqlConnection(MainDataSource.Instance.LocateDataSource("market_data"));
        StringBuilder sb = new StringBuilder();
        DateTime modified=DateTime.Now;
        sb.Append("select symbol,effective_date,ratio,applied,applied_least_recent,applied_most_recent,modified,created from splits ");
        sb.Append(" where symbol='").Append(symbol).Append("'");
        sb.Append(" order by symbol,effective_date desc");
        strQuery = sb.ToString();
        sqlCommand = new MySqlCommand(strQuery, sqlConnection);
        sqlCommand.CommandTimeout = SqlUtils.COMMAND_TIMEOUT;
        sqlDataReader=sqlCommand.ExecuteReader();
        while(sqlDataReader.Read())
        {
          Split split=new Split();
          split.Symbol=sqlDataReader.GetString(0);
          split.EffectiveDate=sqlDataReader.GetDateTime(1);
          split.StrRatio=sqlDataReader.GetString(2);
          split.Applied=sqlDataReader.GetInt32(3)==0?false:true;
          if(!sqlDataReader.IsDBNull(4))split.AppliedLeastRecent=sqlDataReader.GetDateTime(4);
          if(!sqlDataReader.IsDBNull(5))split.AppliedMostRecent=sqlDataReader.GetDateTime(5);
          if(!sqlDataReader.IsDBNull(6))split.Modified=sqlDataReader.GetDateTime(6);
          if(!sqlDataReader.IsDBNull(7))split.Created=sqlDataReader.GetDateTime(7);
          splits.Add(split);
        }
        return splits;
      }
      catch (Exception exception)
      {
        MDTrace.WriteLine(LogLevel.DEBUG,exception);
        MDTrace.WriteLine(LogLevel.DEBUG,"Query was '" + strQuery + "'");
        return null;
      }
      finally
      {
				if(null!=sqlCommand)sqlCommand.Dispose();
        if (null != sqlConnection) sqlConnection.Close();
      }
    }
    public static Splits GetSplits()
    {
      MySqlConnection sqlConnection = null;
			MySqlCommand sqlCommand=null; 
      MySqlDataReader sqlDataReader=null;
      String strQuery = null;
      Splits splits=new Splits();                                

      try
      {
        sqlConnection = SqlUtils.CreateMySqlConnection(MainDataSource.Instance.LocateDataSource("market_data"));
        StringBuilder sb = new StringBuilder();
        DateTime modified=DateTime.Now;
        sb.Append("select symbol,effective_date,ratio,applied,applied_least_recent,applied_most_recent,modified,created from splits order by symbol,effective_date desc");
        strQuery = sb.ToString();
        sqlCommand = new MySqlCommand(strQuery, sqlConnection);
        sqlCommand.CommandTimeout = SqlUtils.COMMAND_TIMEOUT;
        sqlDataReader=sqlCommand.ExecuteReader();
        while(sqlDataReader.Read())
        {
          Split split=new Split();
          split.Symbol=sqlDataReader.GetString(0);
          split.EffectiveDate=sqlDataReader.GetDateTime(1);
          split.StrRatio=sqlDataReader.GetString(2);
          split.Applied=sqlDataReader.GetInt32(3)==0?false:true;
          if(!sqlDataReader.IsDBNull(4))split.AppliedLeastRecent=sqlDataReader.GetDateTime(4);
          if(!sqlDataReader.IsDBNull(5))split.AppliedMostRecent=sqlDataReader.GetDateTime(5);
          if(!sqlDataReader.IsDBNull(6))split.Modified=sqlDataReader.GetDateTime(6);
          if(!sqlDataReader.IsDBNull(7))split.Created=sqlDataReader.GetDateTime(7);
          splits.Add(split);
        }
        return splits;
      }
      catch (Exception exception)
      {
        MDTrace.WriteLine(LogLevel.DEBUG,exception);
        MDTrace.WriteLine(LogLevel.DEBUG,"Query was '" + strQuery + "'");
        return null;
      }
      finally
      {
				if(null!=sqlCommand)sqlCommand.Dispose();
        if (null != sqlConnection) sqlConnection.Close();
      }
    }
    public static bool InsertSplits(Splits splits)
    {
      MySqlConnection sqlConnection = null;
      MySqlTransaction sqlTransaction = null;
			MySqlCommand sqlCommand=null;
      String strQuery = null;

      try
      {
        sqlConnection = SqlUtils.CreateMySqlConnection(MainDataSource.Instance.LocateDataSource("market_data"));
        sqlTransaction = sqlConnection.BeginTransaction(System.Data.IsolationLevel.ReadCommitted);
        StringBuilder sb = new StringBuilder();
        DateTime modified=DateTime.Now;
        DateTime created=modified;
        foreach(Split split in splits)
        {
          sb=new StringBuilder();
          if(ContainsSplit(split))continue;
          sb.Append("insert into splits (symbol,effective_date,ratio,applied,applied_least_recent,applied_most_recent,modified,created) ");
          sb.Append("values(");
          sb.Append("'").Append(split.Symbol).Append("'").Append(",");
          sb.Append("'").Append(SqlUtils.SqlDate(split.EffectiveDate)).Append("'").Append(",");
          sb.Append("'").Append(split.StrRatio).Append("'").Append(",");
          sb.Append("").Append(split.Applied).Append("").Append(",");
          if(split.Applied&&(Utility.IsEpoch(split.AppliedLeastRecent)||Utility.IsEpoch(split.AppliedMostRecent)))
          {
            MDTrace.WriteLine(LogLevel.DEBUG,"Applied split requires LeastRecentDate and MostRecentDate to be set.");
            continue;
          }
          if(!Utility.IsEpoch(split.AppliedLeastRecent))sb.Append("'").Append(SqlUtils.SqlDate(split.AppliedLeastRecent)).Append("'").Append(",");
          else sb.Append("null,");
          if(!Utility.IsEpoch(split.AppliedLeastRecent))sb.Append("'").Append(SqlUtils.SqlDate(split.AppliedMostRecent)).Append("'").Append(",");
          else sb.Append("null,");
          sb.Append("'").Append(SqlUtils.SqlDate(modified)).Append("'").Append(",");
          sb.Append("'").Append(SqlUtils.SqlDate(modified)).Append("'").Append("");
          sb.Append(")");
          strQuery = sb.ToString();
          sqlCommand = new MySqlCommand(strQuery, sqlConnection, sqlTransaction);
          sqlCommand.CommandTimeout = SqlUtils.COMMAND_TIMEOUT;
          sqlCommand.ExecuteNonQuery();
        }
        sqlTransaction.Commit();
        return true;
      }
      catch (Exception exception)
      {
        MDTrace.WriteLine(LogLevel.DEBUG,exception);
        MDTrace.WriteLine(LogLevel.DEBUG,"Query was '" + strQuery + "'");
        return false;
      }
      finally
      {
				if(null!=sqlCommand)sqlCommand.Dispose();
				if(null!=sqlTransaction)sqlTransaction.Dispose();
        if (null != sqlConnection) sqlConnection.Close();
      }
    }
    private static bool DeleteSplits(Splits splits, MySqlConnection sqlConnection, MySqlTransaction sqlTransaction)
    {
      foreach(Split split in splits)DeleteSplit(split,sqlConnection,sqlTransaction);
      return true;
    }
    private static bool DeleteSplit(Split split, MySqlConnection sqlConnection, MySqlTransaction sqlTransaction)
    {
      StringBuilder sb = new StringBuilder();
      String strQuery = null;

      try
      {
        sb.Append("delete from splits where ");
        sb.Append("symbol='").Append(split.Symbol).Append("'");
        sb.Append(" and ");
        sb.Append("effective_date='").Append(SqlUtils.SqlDate(split.EffectiveDate)).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
      {
      }
    }
  }
}
