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

namespace MarketData.DataAccess
{
  public class OptionsDA
  {
    private OptionsDA()
    {
    }
    public static List<String> GetOptionsSymbolIn(List<String> symbols)
    {
      MySqlConnection sqlConnection = null;
      MySqlDataReader sqlDataReader = null;
			MySqlCommand sqlCommand=null;
      String strQuery = null;
      List<String> optionSymbols = new List<String>();

      try
      {
        StringBuilder sb = new StringBuilder();
        sqlConnection = SqlUtils.CreateMySqlConnection(MainDataSource.Instance.LocateDataSource("market_data"));
        sb.Append("select distinct symbol from options where symbol in ").Append(SqlUtils.CreateInClause(symbols)).Append(" order by symbol asc");
        strQuery = sb.ToString();
        sqlCommand = new MySqlCommand(strQuery, sqlConnection);
        sqlCommand.CommandTimeout = SqlUtils.COMMAND_TIMEOUT;
        sqlDataReader = sqlCommand.ExecuteReader();
        while (sqlDataReader.Read())
        {
          optionSymbols.Add(sqlDataReader.GetString(0));
        }
        return optionSymbols;
      }
      catch (Exception exception)
      {
        MDTrace.WriteLine(LogLevel.DEBUG,exception);
        return null;
      }
      finally
      {
				if(null!=sqlCommand)sqlCommand.Dispose();
        if (null != sqlDataReader) {sqlDataReader.Close();sqlDataReader.Dispose();}
        if (null != sqlConnection) sqlConnection.Close();
      }
    }
    public static Options GetOptions(String symbol, DateTime earliestDate)
    {
      MySqlConnection sqlConnection = null;
      MySqlDataReader sqlDataReader = null;
			MySqlCommand sqlCommand=null;
      String strQuery = null;
      Options options = new Options();

      try
      {
        StringBuilder sb = new StringBuilder();
        sqlConnection = SqlUtils.CreateMySqlConnection(MainDataSource.Instance.LocateDataSource("market_data"));
        sb.Append("select symbol, expiration_date,option_type,strike,bid,ask,volume,open_interest,modified from options ");
        sb.Append("where symbol='").Append(symbol).Append("'");
        sb.Append(" and expiration_date>='").Append(Utility.DateTimeToStringYYYYHMMHDD(earliestDate)).Append("'");
        sb.Append(" order by option_type,expiration_date asc, strike desc");
        strQuery = sb.ToString();
        sqlCommand = new MySqlCommand(strQuery, sqlConnection);
        sqlCommand.CommandTimeout = SqlUtils.COMMAND_TIMEOUT;
        sqlDataReader = sqlCommand.ExecuteReader();
        while (sqlDataReader.Read())
        {
          Option option = new Option();
          option.Symbol = sqlDataReader.GetString(0);
          option.Expiration = sqlDataReader.GetDateTime(1);
          option.Type = ("C".Equals(sqlDataReader.GetString(2)) ? OptionTypeEnum.CallOption : OptionTypeEnum.PutOption);
          if (!sqlDataReader.IsDBNull(3)) option.Strike = sqlDataReader.GetDouble(3);
          else option.Strike = double.NaN;
          if (!sqlDataReader.IsDBNull(4)) option.Bid = sqlDataReader.GetDouble(4);
          else option.Bid = double.NaN;
          if (!sqlDataReader.IsDBNull(5)) option.Ask = sqlDataReader.GetDouble(5);
          else option.Ask = double.NaN;
          if (!sqlDataReader.IsDBNull(6)) option.Volume = sqlDataReader.GetInt32(6);
          else option.Ask = double.NaN;
          if (!sqlDataReader.IsDBNull(7)) option.OpenInterest = sqlDataReader.GetDouble(7);
          else option.Ask = double.NaN;
          if (!sqlDataReader.IsDBNull(8)) option.Modified = sqlDataReader.GetDateTime(8);
          else option.Modified = Utility.Epoch;
          options.Add(option);
        }
        return options;
      }
      catch (Exception exception)
      {
        MDTrace.WriteLine(LogLevel.DEBUG,exception);
        return null;
      }
      finally
      {
				if(null!=sqlCommand)sqlCommand.Dispose();
        if (null != sqlDataReader) {sqlDataReader.Close();sqlDataReader.Dispose();}
        if (null != sqlConnection) sqlConnection.Close();
      }
    }
    public static Options GetOptions(String symbol, DateTime earliestDate,OptionTypeEnum optionType)
    {
      MySqlConnection sqlConnection = null;
      MySqlDataReader sqlDataReader = null;
      MySqlCommand sqlCommand=null;
      String strQuery = null;
      Options options = new Options();

      try
      {
        StringBuilder sb = new StringBuilder();
        sqlConnection = SqlUtils.CreateMySqlConnection(MainDataSource.Instance.LocateDataSource("market_data"));
        sb.Append("select symbol, expiration_date,option_type,strike,bid,ask,volume,open_interest,modified from options ");
        sb.Append("where symbol='").Append(symbol).Append("'");
        sb.Append(" and expiration_date>='").Append(Utility.DateTimeToStringYYYYHMMHDD(earliestDate)).Append("'");
        sb.Append(" and option_type='").Append(optionType.Equals(OptionTypeEnum.CallOption) ? "C" : "P").Append("'");
        sb.Append(" order by option_type,expiration_date asc, strike desc");
        strQuery = sb.ToString();
        sqlCommand = new MySqlCommand(strQuery, sqlConnection);
        sqlCommand.CommandTimeout = SqlUtils.COMMAND_TIMEOUT;
        sqlDataReader = sqlCommand.ExecuteReader();
        while (sqlDataReader.Read())
        {
          Option option = new Option();
          option.Symbol = sqlDataReader.GetString(0);
          option.Expiration = sqlDataReader.GetDateTime(1);
          option.Type = ("C".Equals(sqlDataReader.GetString(2)) ? OptionTypeEnum.CallOption : OptionTypeEnum.PutOption);
          if (!sqlDataReader.IsDBNull(3)) option.Strike = sqlDataReader.GetDouble(3);
          else option.Strike = double.NaN;
          if (!sqlDataReader.IsDBNull(4)) option.Bid = sqlDataReader.GetDouble(4);
          else option.Bid = double.NaN;
          if (!sqlDataReader.IsDBNull(5)) option.Ask = sqlDataReader.GetDouble(5);
          else option.Ask = double.NaN;
          if (!sqlDataReader.IsDBNull(6)) option.Volume = sqlDataReader.GetInt32(6);
          else option.Ask = double.NaN;
          if (!sqlDataReader.IsDBNull(7)) option.OpenInterest = sqlDataReader.GetDouble(7);
          else option.Ask = double.NaN;
          if (!sqlDataReader.IsDBNull(8)) option.Modified = sqlDataReader.GetDateTime(8);
          else option.Modified = Utility.Epoch;
          options.Add(option);
        }
        return options;
      }
      catch (Exception exception)
      {
        MDTrace.WriteLine(LogLevel.DEBUG,exception);
        return null;
      }
      finally
      {
        if(null!=sqlCommand)sqlCommand.Dispose();
        if (null != sqlDataReader) {sqlDataReader.Close();sqlDataReader.Dispose();}
        if (null != sqlConnection) sqlConnection.Close();
      }
    }
    public static Options GetOptions(String symbol)
    {
      MySqlConnection sqlConnection = null;
      MySqlDataReader sqlDataReader = null;
			MySqlCommand sqlCommand=null;
      String strQuery = null;
      Options options = new Options();

      try
      {
        StringBuilder sb = new StringBuilder();
        sqlConnection = SqlUtils.CreateMySqlConnection(MainDataSource.Instance.LocateDataSource("market_data"));
        sb.Append("select symbol, expiration_date,option_type,strike,bid,ask,volume,open_interest,modified from options where symbol='").Append(symbol).Append("' order by option_type,expiration_date asc, strike desc");
        strQuery = sb.ToString();
        sqlCommand = new MySqlCommand(strQuery, sqlConnection);
        sqlCommand.CommandTimeout = SqlUtils.COMMAND_TIMEOUT;
        sqlDataReader = sqlCommand.ExecuteReader();
        while (sqlDataReader.Read())
        {
          Option option = new Option();
          option.Symbol = sqlDataReader.GetString(0);
          option.Expiration = sqlDataReader.GetDateTime(1);
          option.Type = ("C".Equals(sqlDataReader.GetString(2)) ?OptionTypeEnum.CallOption : OptionTypeEnum.PutOption);
          if (!sqlDataReader.IsDBNull(3)) option.Strike = sqlDataReader.GetDouble(3);
          else option.Strike = double.NaN;
          if (!sqlDataReader.IsDBNull(4)) option.Bid = sqlDataReader.GetDouble(4);
          else option.Bid = double.NaN;
          if (!sqlDataReader.IsDBNull(5)) option.Ask = sqlDataReader.GetDouble(5);
          else option.Ask = double.NaN;
          if (!sqlDataReader.IsDBNull(6)) option.Volume = sqlDataReader.GetInt32(6);
          else option.Ask = double.NaN;
          if (!sqlDataReader.IsDBNull(7)) option.OpenInterest = sqlDataReader.GetDouble(7);
          else option.Ask = double.NaN;
          if (!sqlDataReader.IsDBNull(8)) option.Modified = sqlDataReader.GetDateTime(8);
          else option.Modified = Utility.Epoch;
          options.Add(option);
        }
        return options;
      }
      catch (Exception exception)
      {
        MDTrace.WriteLine(LogLevel.DEBUG,exception);
        return null;
      }
      finally
      {
				if(null!=sqlCommand)sqlCommand.Dispose();
        if (null != sqlDataReader) {sqlDataReader.Close();sqlDataReader.Dispose();}
        if (null != sqlConnection) sqlConnection.Close();
      }
    }
    public static Options GetOptions(String symbol,OptionTypeEnum optionType)
    {
      MySqlConnection sqlConnection = null;
      MySqlDataReader sqlDataReader = null;
      MySqlCommand sqlCommand=null;
      String strQuery = null;
      Options options = new Options();

      try
      {
        StringBuilder sb = new StringBuilder();
        sqlConnection = SqlUtils.CreateMySqlConnection(MainDataSource.Instance.LocateDataSource("market_data"));
        sb.Append("select symbol, expiration_date,option_type,strike,bid,ask,volume,open_interest,modified from options where symbol='").Append(symbol).Append("'");
        sb.Append(" and option_type='").Append(optionType.Equals(OptionTypeEnum.CallOption)?"C":"P").Append("'");
        sb.Append(" order by option_type,expiration_date asc, strike desc");
        strQuery = sb.ToString();
        sqlCommand = new MySqlCommand(strQuery, sqlConnection);
        sqlCommand.CommandTimeout = SqlUtils.COMMAND_TIMEOUT;
        sqlDataReader = sqlCommand.ExecuteReader();
        while (sqlDataReader.Read())
        {
          Option option = new Option();
          option.Symbol = sqlDataReader.GetString(0);
          option.Expiration = sqlDataReader.GetDateTime(1);
          option.Type = ("C".Equals(sqlDataReader.GetString(2)) ? OptionTypeEnum.CallOption : OptionTypeEnum.PutOption);
          if (!sqlDataReader.IsDBNull(3)) option.Strike = sqlDataReader.GetDouble(3);
          else option.Strike = double.NaN;
          if (!sqlDataReader.IsDBNull(4)) option.Bid = sqlDataReader.GetDouble(4);
          else option.Bid = double.NaN;
          if (!sqlDataReader.IsDBNull(5)) option.Ask = sqlDataReader.GetDouble(5);
          else option.Ask = double.NaN;
          if (!sqlDataReader.IsDBNull(6)) option.Volume = sqlDataReader.GetInt32(6);
          else option.Ask = double.NaN;
          if (!sqlDataReader.IsDBNull(7)) option.OpenInterest = sqlDataReader.GetDouble(7);
          else option.Ask = double.NaN;
          if (!sqlDataReader.IsDBNull(8)) option.Modified = sqlDataReader.GetDateTime(8);
          else option.Modified = Utility.Epoch;
          options.Add(option);
        }
        return options;
      }
      catch (Exception exception)
      {
        MDTrace.WriteLine(LogLevel.DEBUG,exception);
        return null;
      }
      finally
      {
        if(null!=sqlCommand)sqlCommand.Dispose();
        if (null != sqlDataReader) {sqlDataReader.Close();sqlDataReader.Dispose();}
        if (null != sqlConnection) sqlConnection.Close();
      }
    }
    public static bool DeleteOptions(String symbol)
    {
      MySqlConnection sqlConnection = null;
      MySqlCommand sqlCommand = null;
      String strQuery = null;
      try
      {
        StringBuilder sb = new StringBuilder();
        sqlConnection = SqlUtils.CreateMySqlConnection(MainDataSource.Instance.LocateDataSource("market_data"));
        sb.Append("delete from options where symbol='").Append(symbol).Append("' ");
        strQuery = sb.ToString();
        sqlCommand = new MySqlCommand(strQuery, sqlConnection);
        sqlCommand.CommandTimeout = SqlUtils.COMMAND_TIMEOUT;
        sqlCommand.ExecuteNonQuery();
        sqlCommand.Dispose();
        sqlCommand = null;
        return true;
      }
      catch (Exception exception)
      {
        MDTrace.WriteLine(LogLevel.DEBUG, exception);
        return false;
      }
      finally
      {
        if (null != sqlCommand) { sqlCommand.Dispose(); sqlCommand = null; }
        if (null != sqlConnection) { sqlConnection.Close(); sqlConnection = null; }
      }
    }
    private static bool DeleteOption(Option option, MySqlTransaction sqlTransaction)
    {
      MySqlConnection sqlConnection = null;
      MySqlCommand sqlCommand = null;
      String strQuery = null;
      try
      {
        StringBuilder sb = new StringBuilder();
        sqlConnection = SqlUtils.CreateMySqlConnection(MainDataSource.Instance.LocateDataSource("market_data"));
        sb.Append("delete from options where symbol=").Append(SqlUtils.AddQuotes(option.Symbol));
        sb.Append(" and expiration_date=").Append(SqlUtils.AddQuotes(Utility.DateTimeToStringYYYYHMMHDD(option.Expiration)));
        sb.Append(" and strike=").Append(Utility.FormatNumber(option.Strike,2));
        sb.Append(" and option_type=").Append(SqlUtils.AddQuotes(option.Type.Equals(OptionTypeEnum.CallOption) ? "C" : "P"));
        strQuery = sb.ToString();
        sqlCommand = new MySqlCommand(strQuery, sqlConnection, sqlTransaction);
        sqlCommand.CommandTimeout = SqlUtils.COMMAND_TIMEOUT;
        sqlCommand.ExecuteNonQuery();
        sqlCommand.Dispose();
        sqlCommand = null;
        return true;
      }
      catch (Exception exception)
      {
        MDTrace.WriteLine(LogLevel.DEBUG,exception);
        return false;
      }
      finally
      {
        if (null != sqlCommand) { sqlCommand.Dispose(); sqlCommand = null; }
        if (null != sqlConnection) { sqlConnection.Close(); sqlConnection = null; }
      }
    }
    public static bool AddOptions(Options options)
    {
      foreach (Option option in options)
      {
       AddOption(option);
      }
      return true;
    }
    public static bool AddOption(Option option)
    {
      MySqlConnection sqlConnection = null;
      MySqlTransaction sqlTransaction = null;
			MySqlCommand sqlCommand=null;
      String strQuery = null;

      try
      {
        DateTime modified = DateTime.Now;
        if (null == option) return false;
        sqlConnection = SqlUtils.CreateMySqlConnection(MainDataSource.Instance.LocateDataSource("market_data"));
        sqlTransaction = sqlConnection.BeginTransaction(System.Data.IsolationLevel.ReadCommitted);
        DeleteOption(option,sqlTransaction);
        StringBuilder sb=new StringBuilder();
        sb.Append("insert into options(symbol,expiration_date,option_type,strike,last_price,change_price,bid,ask,volume,open_interest,modified)values(");
        sb.Append(SqlUtils.AddQuotes(option.Symbol)).Append(",");
        sb.Append(SqlUtils.AddQuotes((Utility.DateTimeToStringYYYYHMMHDD(option.Expiration)))).Append(",");
        sb.Append(SqlUtils.AddQuotes(option.Type.Equals(OptionTypeEnum.CallOption)?"C":"P")).Append(",");
        if (!double.IsNaN(option.Strike)) sb.Append(Utility.FormatNumber(option.Strike,2)).Append(",");
        else sb.Append("null").Append(",");
        if (!double.IsNaN(option.Last)) sb.Append(option.Last).Append(",");
        else sb.Append("null").Append(",");
        if (!double.IsNaN(option.Change)) sb.Append(option.Change).Append(",");
        else sb.Append("null").Append(",");
        if (!double.IsNaN(option.Bid)) sb.Append(option.Bid).Append(",");
        else sb.Append("null").Append(",");
        if (!double.IsNaN(option.Ask)) sb.Append(option.Ask).Append(",");
        else sb.Append("null").Append(",");
        if (!double.IsNaN(option.Volume)) sb.Append(option.Volume).Append(",");
        else sb.Append("null").Append(",");
        if (!double.IsNaN(option.OpenInterest)) sb.Append(option.OpenInterest).Append(",");
        else sb.Append("null").Append(",");
        sb.Append(SqlUtils.AddQuotes(Utility.DateTimeToStringYYYYHMMHDD(modified)));
        sb.Append(")");
        strQuery = sb.ToString();
        sqlCommand = new MySqlCommand(strQuery, sqlConnection, sqlTransaction);
        sqlCommand.CommandTimeout = SqlUtils.COMMAND_TIMEOUT;
        sqlCommand.ExecuteNonQuery();
        sqlTransaction.Commit();
        sqlTransaction.Dispose();
        sqlTransaction=null;
        return true;
      }
      catch (Exception exception)
      {
        MDTrace.WriteLine(LogLevel.DEBUG,exception);
        return false;
      }
      finally
      {
				if(null!=sqlCommand)sqlCommand.Dispose();
        if (null != sqlConnection) sqlConnection.Close();
        if (null != sqlTransaction) sqlTransaction.Dispose();
      }
    }
  }
}

