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

namespace MarketData.DataAccess
{
  public class LexicalDA
  {
    private LexicalDA()
    {
    }
    public static bool TruncateLexicon()
    {
      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();
        sb.Append("truncate table lexicon");
        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 bool InsertLexicalElement(LexicalElement lexicalElement)
    {
      LexicalCollection lexicalCollection=new LexicalCollection();
      lexicalCollection.Add(lexicalElement);
      InsertLexicalCollection(lexicalCollection);
      return true;
    }
    public static bool InsertLexicalCollection(LexicalCollection lexicalCollection)
    {
      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(LexicalElement lexicalElement in lexicalCollection)
        {
          sb=new StringBuilder();
          if(ContainsLexicalElement(lexicalElement))continue;
          sb.Append("insert into lexicon (word,sentiment,part_of_speech) ");
          sb.Append("values(");
          sb.Append("'").Append(lexicalElement.Word).Append("'").Append(",");
          sb.Append("'").Append(lexicalElement.Sentiment).Append("'").Append(",");
          if(null!=lexicalElement.PartOfSpeech)sb.Append("'").Append(lexicalElement.PartOfSpeech).Append("'");
          else  sb.Append("null");
          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();
      }
    }
    public static bool ContainsLexicalElement(LexicalElement lexicalElement)
    {
      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 lexicon where word='").Append(lexicalElement.Word).Append("' ");
        sb.Append("and sentiment='").Append(lexicalElement.Sentiment).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();sqlDataReader.Dispose();}
        if (null != sqlConnection) sqlConnection.Close();
      }
    }
    public static bool UpdateLexicalElement(LexicalElement lexicalElement)
    {
      LexicalCollection lexicalCollection=new LexicalCollection();
      lexicalCollection.Add(lexicalElement);
      return UpdateLexicalElements(lexicalCollection);
    }
    public static bool UpdateLexicalElements(LexicalCollection lexicalCollection)
    {
      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);
        foreach(LexicalElement lexicalElement in lexicalCollection)
        {
          if(!ContainsLexicalElement(lexicalElement))continue;
          if(null==lexicalElement.PartOfSpeech||0==lexicalElement.PartOfSpeech.Length)continue;
          StringBuilder sb = new StringBuilder();
          DateTime modified=DateTime.Now;
          sb.Append("update lexicon set ");
          sb.Append("part_of_speech=").Append("'").Append(lexicalElement.PartOfSpeech).Append("'");
          sb.Append(" where word='").Append(lexicalElement.Word).Append("'").Append(" and ");
          sb.Append("sentiment='").Append(lexicalElement.Sentiment).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 LexicalCollection GetLexicalCollection(String sentiment)
    {
      MySqlConnection sqlConnection = null;
      MySqlCommand sqlCommand=null; 
      MySqlDataReader sqlDataReader=null;
      LexicalCollection lexicalCollection=new LexicalCollection();
      String strQuery = null;

      try
      {
        sqlConnection = SqlUtils.CreateMySqlConnection(MainDataSource.Instance.LocateDataSource("market_data"));
        StringBuilder sb = new StringBuilder();
        DateTime modified=DateTime.Now;
        sb.Append("select word,sentiment,part_of_speech from lexicon ");
        sb.Append(" where sentiment='").Append(sentiment).Append("'");
        sb.Append(" order by word desc");
        strQuery = sb.ToString();
        sqlCommand = new MySqlCommand(strQuery, sqlConnection);
        sqlCommand.CommandTimeout = SqlUtils.COMMAND_TIMEOUT;
        sqlDataReader=sqlCommand.ExecuteReader();
        while(sqlDataReader.Read())
        {
          LexicalElement lexicalElement=new LexicalElement();
          lexicalElement.Word=sqlDataReader.GetString(0);
          lexicalElement.Sentiment=sqlDataReader.GetString(1);
          if(!sqlDataReader.IsDBNull(2))lexicalElement.PartOfSpeech=sqlDataReader.GetString(2);
          lexicalCollection.Add(lexicalElement);
        }
        return lexicalCollection;
      }
      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 != sqlDataReader) {sqlDataReader.Close();sqlDataReader.Dispose();}
        if (null != sqlConnection) sqlConnection.Close();
      }
    }
    public static LexicalCollection GetLexicalCollection()
    {
      MySqlConnection sqlConnection = null;
      MySqlCommand sqlCommand=null; 
      MySqlDataReader sqlDataReader=null;
      LexicalCollection lexicalCollection=new LexicalCollection();
      String strQuery = null;

      try
      {
        sqlConnection = SqlUtils.CreateMySqlConnection(MainDataSource.Instance.LocateDataSource("market_data"));
        StringBuilder sb = new StringBuilder();
        DateTime modified=DateTime.Now;
        sb.Append("select word,sentiment,part_of_speech from lexicon ");
        sb.Append(" order by word desc");
        strQuery = sb.ToString();
        sqlCommand = new MySqlCommand(strQuery, sqlConnection);
        sqlCommand.CommandTimeout = SqlUtils.COMMAND_TIMEOUT;
        sqlDataReader=sqlCommand.ExecuteReader();
        while(sqlDataReader.Read())
        {
          LexicalElement lexicalElement=new LexicalElement();
          lexicalElement.Word=sqlDataReader.GetString(0);
          lexicalElement.Sentiment=sqlDataReader.GetString(1);
          if(!sqlDataReader.IsDBNull(2))lexicalElement.PartOfSpeech=sqlDataReader.GetString(2);
          lexicalCollection.Add(lexicalElement);
        }
        return lexicalCollection;
      }
      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 != sqlDataReader) {sqlDataReader.Close();sqlDataReader.Dispose();}
        if (null != sqlConnection) sqlConnection.Close();
      }
    }
    private static bool DeleteLexicalCollection(LexicalCollection lexicalCollection, MySqlConnection sqlConnection, MySqlTransaction sqlTransaction)
    {
      foreach(LexicalElement lexicalElement in lexicalCollection)DeleteLexicalElement(lexicalElement,sqlConnection,sqlTransaction);
      return true;
    }
    private static bool DeleteLexicalElement(LexicalElement lexicalElement, MySqlConnection sqlConnection, MySqlTransaction sqlTransaction)
    {
      StringBuilder sb = new StringBuilder();
      String strQuery = null;

      try
      {
        sb.Append("delete from lexicon where ");
        sb.Append("word='").Append(lexicalElement.Word).Append("'");
        sb.Append(" and ");
        sb.Append("sentiment='").Append(lexicalElement.Sentiment).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
      {
      }
    }
  }
}
