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

namespace MarketData.DataAccess
{
  public class MaintenanceDA
  {
    private MaintenanceDA()
    {
    }

    public static bool OptimizeDatabase()
    {
      MySqlConnection sqlConnection = null;
      String strQuery = null;
      int COMMAND_TIMEOUT = 600; // 10 minutes
      List<String> tasks = new List<String>
      {
        "PURGE BINARY LOGS BEFORE NOW();",
        "USE market_data;OPTIMIZE NO_WRITE_TO_BINLOG TABLE analystpricetarget;",
        "USE market_data;OPTIMIZE NO_WRITE_TO_BINLOG TABLE analystratings;",
        "USE market_data;OPTIMIZE NO_WRITE_TO_BINLOG TABLE balancesheet;",
        "USE market_data;OPTIMIZE NO_WRITE_TO_BINLOG TABLE incomestatement;",
        "USE market_data;OPTIMIZE NO_WRITE_TO_BINLOG TABLE cashflowstatement;",
        "USE market_data;OPTIMIZE NO_WRITE_TO_BINLOG TABLE dividendhistory;",
        "USE market_data;OPTIMIZE NO_WRITE_TO_BINLOG TABLE etfholdings;",
        "USE market_data;OPTIMIZE NO_WRITE_TO_BINLOG TABLE fundamentals;",
        "USE market_data;OPTIMIZE NO_WRITE_TO_BINLOG TABLE historical;",
        "USE market_data;OPTIMIZE NO_WRITE_TO_BINLOG TABLE insidertransaction;",
        "USE market_data;OPTIMIZE NO_WRITE_TO_BINLOG TABLE options;",
        "USE market_data;OPTIMIZE NO_WRITE_TO_BINLOG TABLE prices;",
        "USE market_data;OPTIMIZE NO_WRITE_TO_BINLOG TABLE secfilings;",
        "USE market_data;OPTIMIZE NO_WRITE_TO_BINLOG TABLE valuations;",
        "USE market_data;OPTIMIZE NO_WRITE_TO_BINLOG TABLE yieldcurve;",
        "USE portfolio_data;OPTIMIZE NO_WRITE_TO_BINLOG TABLE accounts;",
        "USE portfolio_data;OPTIMIZE NO_WRITE_TO_BINLOG TABLE cash;",
        "USE portfolio_data;OPTIMIZE NO_WRITE_TO_BINLOG TABLE trades;",
        "USE portfolio_data;OPTIMIZE NO_WRITE_TO_BINLOG TABLE watchlist;",
        "USE portfolio_data;OPTIMIZE NO_WRITE_TO_BINLOG TABLE watchlists;"
      };

      try
      {
        sqlConnection = SqlUtils.CreateMySqlConnection(MainDataSource.Instance.LocateDataSource("market_data"));
        foreach (String task in tasks)
        {
          strQuery = task;
          MDTrace.WriteLine(LogLevel.DEBUG, $"Executing {task}");
          using MySqlCommand sqlCommand = new MySqlCommand(task, sqlConnection);
          sqlCommand.CommandTimeout = COMMAND_TIMEOUT;
          sqlCommand.ExecuteNonQuery();
        }
        return true;
      }
      catch (Exception exception)
      {
        MDTrace.WriteLine(LogLevel.DEBUG, exception);
        MDTrace.WriteLine(LogLevel.DEBUG, "Query was '" + strQuery + "'");
        return false;
      }
      finally
      {
        if (null != sqlConnection) sqlConnection.Close();
      }
    }
  }
}