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

namespace MarketData.DataAccess
{
  public class CompanyProfileDA
  {
    private CompanyProfileDA()
    {
    }
// ***********************************************************************************************************
// ************************************** C O M P A N Y   P R O F I L E  *************************************
// ***********************************************************************************************************
    public static bool UpdateCompanyProfile(CompanyProfile companyProfile)
    {
      MySqlConnection sqlConnection = null;
      MySqlTransaction sqlTransaction = null;
			MySqlCommand sqlCommand=null;
      String strQuery = null;

      try
      {
        if (null == companyProfile || null == companyProfile.Symbol) return false;
        if(!PricingDA.SecurityExists(companyProfile.Symbol))return false;
        sqlConnection = SqlUtils.CreateMySqlConnection(MainDataSource.Instance.LocateDataSource("market_data"));
        sqlTransaction = sqlConnection.BeginTransaction(System.Data.IsolationLevel.ReadCommitted);

        if(null!=companyProfile.Industry || null!=companyProfile.Sector)
        {
          StringBuilder sb = new StringBuilder();
          sb.Append("update securitymaster ");
          sb.Append("set ");
          if((null!=companyProfile.Sector && !"".Equals(companyProfile.Sector)) && (null != companyProfile.Industry && !"".Equals(companyProfile.Industry)))
          {
            sb.Append("Sector=").Append(SqlUtils.AddQuotes(companyProfile.Sector)).Append(", ");
            sb.Append("Industry=").Append(SqlUtils.AddQuotes(companyProfile.Industry)).Append(" ");
          }
          else if(null!=companyProfile.Industry && !"".Equals(companyProfile.Industry))
          {
            sb.Append("Industry=").Append(SqlUtils.AddQuotes(companyProfile.Industry)).Append(" ");
          }
          else if(null!=companyProfile.Sector&&!"".Equals(companyProfile.Industry))
          {
            sb.Append("Sector=").Append(SqlUtils.AddQuotes(companyProfile.Sector)).Append(" ");
          }
          sb.Append(" where symbol=").Append(SqlUtils.AddQuotes(companyProfile.Symbol));
          strQuery = sb.ToString();
          sqlCommand = new MySqlCommand(strQuery, sqlConnection, sqlTransaction);
          sqlCommand.CommandTimeout = SqlUtils.COMMAND_TIMEOUT;
          sqlCommand.ExecuteNonQuery();
        }
        if(!CompanyProfileDetailsExists(companyProfile,sqlConnection,sqlTransaction))InsertCompanyProfileDescription(companyProfile,sqlConnection,sqlTransaction);
        else UpdateCompanyProfileDescription(companyProfile,sqlConnection,sqlTransaction);
        sqlTransaction.Commit();
        return true;
      }
      catch (Exception exception)
      {
        MDTrace.WriteLine(LogLevel.DEBUG,exception);
        return false;
      }
      finally
      {
				if(null!=sqlCommand)sqlCommand.Dispose();
        if (null != sqlTransaction) sqlTransaction.Dispose();
        if (null != sqlConnection) sqlConnection.Close();
      }
    }
    public static CompanyProfiles GetCompanyProfiles()
    {
      CompanyProfiles companyProfiles=new CompanyProfiles();
      MySqlConnection sqlConnection = null;
      MySqlDataReader sqlDataReader = null;
      MySqlCommand sqlCommand=null;
      String strQuery = null;

      try
      {
        StringBuilder sb = new StringBuilder();
        sqlConnection = SqlUtils.CreateMySqlConnection(MainDataSource.Instance.LocateDataSource("market_data"));
        sb.Append("select sm.symbol,sm.sector,sm.industry,sm.security_type,sm.company,cp.description,cp.pricing_source,cp.can_roll_previous,cp.freeze_pricing from securitymaster sm left outer join companyprofile cp on sm.symbol=cp.symbol");
        strQuery = sb.ToString();
        sqlCommand = new MySqlCommand(strQuery, sqlConnection);
        sqlCommand.CommandTimeout = SqlUtils.COMMAND_TIMEOUT;
        sqlDataReader = sqlCommand.ExecuteReader();
        while(sqlDataReader.Read())
        {
          CompanyProfile companyProfile = new CompanyProfile();
          companyProfile.Symbol=sqlDataReader.GetString(0);
          if (!sqlDataReader.IsDBNull(1)) companyProfile.Sector = sqlDataReader.GetString(1);
          if (!sqlDataReader.IsDBNull(2)) companyProfile.Industry = sqlDataReader.GetString(2);
          if (!sqlDataReader.IsDBNull(3)) companyProfile.SecurityType = sqlDataReader.GetString(3);
          if (!sqlDataReader.IsDBNull(4)) companyProfile.CompanyName = sqlDataReader.GetString(4);
          if (!sqlDataReader.IsDBNull(5)) companyProfile.Description = sqlDataReader.GetString(5);
          if (!sqlDataReader.IsDBNull(6)) companyProfile.PricingSource = sqlDataReader.GetString(6).ToUpper();
          if (!sqlDataReader.IsDBNull(7)) companyProfile.CanRollPrevious = sqlDataReader.GetBoolean(7);
          if (!sqlDataReader.IsDBNull(8)) companyProfile.FreezePricing = sqlDataReader.GetBoolean(8);
          companyProfiles.Add(companyProfile);
        }
        return companyProfiles;
      }
      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();
      }
    }
    public static CompanyProfile GetCompanyProfile(String symbol)
    {
      MySqlConnection sqlConnection = null;
      MySqlDataReader sqlDataReader = null;
			MySqlCommand sqlCommand=null;
      String strQuery = null;

      try
      {
        StringBuilder sb = new StringBuilder();
        sqlConnection = SqlUtils.CreateMySqlConnection(MainDataSource.Instance.LocateDataSource("market_data"));
        sb.Append("select sm.sector,sm.industry,sm.security_type,sm.company,cp.description,cp.pricing_source,cp.can_roll_previous,cp.freeze_pricing from securitymaster sm left outer join companyprofile cp on sm.symbol=cp.symbol where sm.symbol='");
        sb.Append(symbol).Append("'");
        strQuery = sb.ToString();
        sqlCommand = new MySqlCommand(strQuery, sqlConnection);
        sqlCommand.CommandTimeout = SqlUtils.COMMAND_TIMEOUT;
        sqlDataReader = sqlCommand.ExecuteReader();
        if (!sqlDataReader.Read()) return null;
        CompanyProfile companyProfile = new CompanyProfile();
        companyProfile.Symbol = symbol;
        if (!sqlDataReader.IsDBNull(0)) companyProfile.Sector = sqlDataReader.GetString(0);
        if (!sqlDataReader.IsDBNull(1)) companyProfile.Industry = sqlDataReader.GetString(1);
        if (!sqlDataReader.IsDBNull(2)) companyProfile.SecurityType = sqlDataReader.GetString(2);
        if (!sqlDataReader.IsDBNull(3)) companyProfile.CompanyName = sqlDataReader.GetString(3);
        if (!sqlDataReader.IsDBNull(4)) companyProfile.Description = sqlDataReader.GetString(4);
        if (!sqlDataReader.IsDBNull(5)) companyProfile.PricingSource = sqlDataReader.GetString(5).ToUpper();
        if (!sqlDataReader.IsDBNull(6)) companyProfile.CanRollPrevious = sqlDataReader.GetBoolean(6);
        if (!sqlDataReader.IsDBNull(7)) companyProfile.FreezePricing = sqlDataReader.GetBoolean(7);
        return companyProfile;
      }
      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();
      }
    }

// This handles the actual company profile table where we store additional company related informtion
    private static bool CompanyProfileDetailsExists(CompanyProfile companyProfile,MySqlConnection sqlConnection,MySqlTransaction sqlTransaction)
    {
      MySqlDataReader sqlDataReader=null;
			MySqlCommand sqlCommand=null;
      String strQuery = null;

      try
      {
        if (null == companyProfile || null == companyProfile.Symbol) return false;
        StringBuilder sb = new StringBuilder();
        sb.Append("select count(*) from CompanyProfile where symbol=").Append(SqlUtils.AddQuotes(companyProfile.Symbol)).Append(" and description is not null and description <>''");
        strQuery = sb.ToString();
        sqlCommand = new MySqlCommand(strQuery, sqlConnection, sqlTransaction);
        sqlCommand.CommandTimeout = SqlUtils.COMMAND_TIMEOUT;
        sqlDataReader=sqlCommand.ExecuteReader();
        if(!sqlDataReader.Read())return false;
        return 0==sqlDataReader.GetInt32(0)?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();}
      }
    }
    private static bool InsertCompanyProfileDescription(CompanyProfile companyProfile,MySqlConnection sqlConnection,MySqlTransaction sqlTransaction)
    {
			MySqlCommand sqlCommand=null;
      String strQuery = null;

      try
      {
        if (null == companyProfile || null == companyProfile.Symbol || null==companyProfile.Description || "".Equals(companyProfile.Description.Trim())) return false;
        StringBuilder sb = new StringBuilder();
        sb.Append("insert into CompanyProfile(symbol,description)values(");
        sb.Append(SqlUtils.AddQuotes(companyProfile.Symbol)).Append(",");
        sb.Append(SqlUtils.ToSqlString(companyProfile.Description.Trim()));
        sb.Append(")");
        strQuery = sb.ToString();
        sqlCommand = new MySqlCommand(strQuery, sqlConnection, sqlTransaction);
        sqlCommand.CommandTimeout = SqlUtils.COMMAND_TIMEOUT;
        sqlCommand.ExecuteNonQuery();
        return true;
      }
      catch (Exception exception)
      {
        MDTrace.WriteLine(LogLevel.DEBUG,exception);
        return false;
      }
      finally
      {
				if(null!=sqlCommand)sqlCommand.Dispose();
      }
    }
    private static bool UpdateCompanyProfileDescription(CompanyProfile companyProfile,MySqlConnection sqlConnection,MySqlTransaction sqlTransaction)
    {
			MySqlCommand sqlCommand=null;
      String strQuery = null;

      try
      {
        if (null == companyProfile || null == companyProfile.Symbol || null==companyProfile.Description || "".Equals(companyProfile.Description)) return false;
        StringBuilder sb = new StringBuilder();
        sb.Append("update CompanyProfile set description=").Append(SqlUtils.ToSqlString(companyProfile.Description));
        sb.Append(" where symbol=").Append(SqlUtils.AddQuotes(companyProfile.Symbol));
        strQuery = sb.ToString();
        sqlCommand = new MySqlCommand(strQuery, sqlConnection, sqlTransaction);
        sqlCommand.CommandTimeout = SqlUtils.COMMAND_TIMEOUT;
        sqlCommand.ExecuteNonQuery();
        return true;
      }
      catch (Exception exception)
      {
        MDTrace.WriteLine(LogLevel.DEBUG,exception);
        return false;
      }
      finally
      {
				if(null!=sqlCommand)sqlCommand.Dispose();
      }
    }
  }
}
