#include "stdafx.h"

#include "mysql_sql_schema_rename.h"
#include "grtsqlparser/module_utils.h"
#include "mysql_sql_parser_fe.h"
#include "myx_statement_parser.h"
#include <sstream>


using namespace grt;
using namespace bec;


Mysql_sql_schema_rename::Null_state_keeper::~Null_state_keeper()
{
  _sql_parser->_old_schema_name= std::string();
  _sql_parser->_new_schema_name= std::string();
  _sql_parser->_schema_names_offsets= std::list<int>();
}
#define NULL_STATE_KEEPER Null_state_keeper _nsk(this);


Mysql_sql_schema_rename::Mysql_sql_schema_rename(grt::GRT *grt)
:
Sql_parser_base(grt),
Mysql_sql_parser_base(grt)
{
  NULL_STATE_KEEPER // reset all members to null-values
}


int Mysql_sql_schema_rename::rename_schema_references(
  db_mysql_CatalogRef catalog,
  const std::string &old_schema_name,
  const std::string &new_schema_name)
{
  NULL_STATE_KEEPER

  _catalog= catalog;
  _old_schema_name= old_schema_name;
  _new_schema_name= new_schema_name;

  std::string rename_action_details= strfmt(_("updating references to schema: `%s` -> `%s`"), old_schema_name.c_str(), new_schema_name.c_str());

  {
    std::string msg= strfmt(_("Started %s."), rename_action_details.c_str());
    add_log_message(msg, 0);
  }

  _process_sql_statement= sigc::mem_fun(this, &Mysql_sql_schema_rename::process_sql_statement);
  Mysql_sql_parser_fe sql_parser_fe(_grtm->get_grt());

  ListRef<db_mysql_Schema> schemata= _catalog->schemata();
  for (size_t n= 0, count= schemata.count(); n < count; ++n)
  {
    _active_schema= schemata.get(n);

    // views
    rename_schema_references<db_mysql_View>(
      _active_schema->views(),
      &db_mysql_View::sqlDefinition,
      &db_mysql_View::sqlDefinition,
      0,
      sql_parser_fe);

    // routines
    rename_schema_references<db_mysql_Routine>(
      _active_schema->routines(),
      &db_mysql_Routine::sqlDefinition,
      &db_mysql_Routine::sqlDefinition,
      1,
      sql_parser_fe);

    // tables + triggers
    {
      grt::ListRef<db_mysql_Table> tables= _active_schema->tables();

      // tables
      for (size_t n= 0, count= tables.count(); n < count; ++n)
      {
        // triggers
        rename_schema_references<db_mysql_Trigger>(
          tables.get(n)->triggers(),
          &db_mysql_Trigger::sqlDefinition,
          &db_mysql_Trigger::sqlDefinition,
          1,
          sql_parser_fe);
      }
    }
  }

  {
    std::string msg= strfmt(_("Finished %s."), rename_action_details.c_str()) + " " +
      strfmt(_("Totally processed statements: successful (%i), errors (%i), warnings (%i)."),
        _processed_obj_count, _err_count, _warn_count);
    add_log_message(msg, 0);
  }

  return pr_processed;
}


template<typename T>
void Mysql_sql_schema_rename::rename_schema_references(
  grt::ListRef<T> obj_list,
  grt::StringRef (T::*sql_text_prop_r)() const,
  void (T::*sql_text_prop_w)(const grt::StringRef&),
  int delim_wraping,
  Mysql_sql_parser_fe& sql_parser_fe)
{
  for (size_t n= 0, count= obj_list.count(); n < count; ++n)
  {
    Ref<T> db_obj= obj_list.get(n);
    std::string sql_text= (db_obj.content().*sql_text_prop_r)();
    if (!sql_text.empty())
    {
      static const std::string begin_delim1= "DELIMITER //\n";
      static const std::string begin_delim2= "DELIMITER //\nCREATE PROCEDURE proc()\n";
      static const std::string end_delim= "\n//\nDELIMITER ;\n;\n";

      std::string begin_delim;

      switch (delim_wraping)
      {
      case 1: begin_delim= begin_delim1; break;
      case 2: begin_delim= begin_delim2; break;
      }

      if (delim_wraping)
      {
        sql_text.reserve(sql_text.size() + begin_delim.size() + end_delim.size());
        sql_text.insert(0, begin_delim).append(end_delim);
      }

      _active_obj= db_obj;
      (void) parse_sql_script(sql_parser_fe, sql_text.c_str());
      _active_obj= db_DatabaseObjectRef();

      if (rename_schema_references(sql_text))
      {
        {
          std::string log_msg;
          log_msg
            .append(db_obj.get_metaclass()->get_attribute("caption"))
            .append(" ")
            .append(db_obj->name())
            .append(" updated with regard to new schema name.");
          ++_processed_obj_count;
          add_log_message(log_msg, 0);
        }

        if (delim_wraping)
        {
          sql_text.erase(sql_text.size() - end_delim.size(), end_delim.size());
          sql_text.erase(0, begin_delim.size());
        }

        (db_obj.content().*sql_text_prop_w)(sql_text);
      }
    }
  }
}


int Mysql_sql_schema_rename::process_sql_statement(const MyxSQLTreeItem *tree)
{
  // on parsing error log error message
  if (!tree)
  {
    report_sql_error(_lineno, true, _err_tok_line_pos, _err_tok_len, _err_msg, 2);
    return -1;
  }

  process_sql_statement_item(tree);

  return 0; // success
}


void Mysql_sql_schema_rename::process_sql_statement_item(const MyxSQLTreeItem *item)
{
  {
    // try all rules with dot notation

    if (item->name_equals(sql::_sp_name))
      process_schema_reference_candidate(item, 1);

    // else if (item->name_equals(sql::_opt_component))
      // irrelevant (doesn't refer schema)

    else if (item->name_equals(sql::_function_call_generic))
      process_schema_reference_candidate(item, 1);

    else if (item->name_equals(sql::_table_wild_one))
      process_schema_reference_candidate(item, 1);

    // else if (item->name_equals(sql::_opt_wild))
      // irrelevant (doesn't refer schema)

    else if (item->name_equals(sql::_table_wild))
      process_schema_reference_candidate(item, 2);

    else if (item->name_equals(sql::_simple_ident_q))
      process_schema_reference_candidate(item, 2);

    else if (item->name_equals(sql::_field_ident))
      process_schema_reference_candidate(item, 2);

    else if (item->name_equals(sql::_table_ident))
      process_schema_reference_candidate(item, 1);

    // else if (item->name_equals(sql::_internal_variable_name))
      // irrelevant (doesn't refer schema)

    else if (item->name_equals(sql::_grant_ident))
      process_schema_reference_candidate(item, 1);
  }

  {
    const MyxSQLTreeItem::SubItemList *subitems= item->subitems();
    MyxSQLTreeItem::SubItemList::const_iterator it= subitems->begin();
    MyxSQLTreeItem::SubItemList::const_iterator it_end= subitems->end();
    for (; it != it_end; ++it)
    {
      const MyxSQLTreeItem *subitem= *it;
      if (subitem->subitems()->size())
        process_sql_statement_item(subitem);
    }
  }
}


void Mysql_sql_schema_rename::process_schema_reference_candidate(const MyxSQLTreeItem *item, int dot_count)
{
  const MyxSQLTreeItem *subitem= NULL;
  switch (dot_count)
  {
  case 1:
    subitem= item->subseq(sql::_ident, sql::_46); // 46 == ascii('.')
    break;
  case 2:
    subitem= item->subseq(sql::_ident, sql::_46, sql::_ident, sql::_46); // 46 == ascii('.')
    break;
  }
  if (subitem && (subitem= item->subseq(sql::_ident)) && are_strings_eq(subitem->value(), _old_schema_name.c_str(), _case_sensitive_identifiers))
    _schema_names_offsets.push_back(_splitter->statement_boffset() + subitem->stmt_boffset());
}


bool Mysql_sql_schema_rename::rename_schema_references(std::string &sql_text)
{
  if (!_schema_names_offsets.empty())
  {
    if (_old_schema_name.size() < _new_schema_name.size())
      sql_text.reserve(sql_text.size() + (_new_schema_name.size() - _old_schema_name.size()) * _schema_names_offsets.size());
    for (std::list<int>::reverse_iterator i= _schema_names_offsets.rbegin(); i != _schema_names_offsets.rend(); ++i)
      sql_text.replace(*i, _old_schema_name.size(), _new_schema_name);
    _schema_names_offsets.clear();
    return true;
  }
  return false;
}
