#include "errors_list.h"

//------------------------------------------------------------------------------
ErrorsList::ErrorsList(bec::DBObjectEditorBE* be)
           : _errors_tv(new Gtk::TreeView())
           , _errors_model(Gtk::ListStore::create(_errors_columns))
           , _be(be)
{
  _errors_tv->set_model(_errors_model);

  _errors_tv->append_column("Line"   , _errors_columns.lineno);
  _errors_tv->append_column("Message", _errors_columns.msg);

  _errors_tv->signal_cursor_changed().connect(sigc::mem_fun(*this, &ErrorsList::error_selected));
  _be->set_sql_parser_err_cb(sigc::mem_fun(this, &ErrorsList::add_error));
}

//------------------------------------------------------------------------------
ErrorsList::~ErrorsList()
{
  delete _errors_tv;
}

//------------------------------------------------------------------------------
void ErrorsList::switch_be(bec::DBObjectEditorBE* be)
{
  _be = be;
  _be->set_sql_parser_err_cb(sigc::mem_fun(this, &ErrorsList::add_error));
}

//------------------------------------------------------------------------------
void ErrorsList::clear_list()
{
  _errors_model->clear();
}

//------------------------------------------------------------------------------
int ErrorsList::add_error(const int line, const int err_tok_line_pos, const int err_tok_len, const std::string &err_msg)
{
  Gtk::TreeModel::Row row = *(_errors_model->append());
  std::string msg(err_msg);
  std::replace(msg.begin(), msg.end(), '\n', ' ');
  row[_errors_columns.lineno]    = line;
  row[_errors_columns.msg]       = msg;
  
  _sql_parser_err_cb(line, err_tok_line_pos, err_tok_len, err_msg);
  
  return 0;
}
    
//------------------------------------------------------------------------------
Gtk::TreeView& ErrorsList::widget()
{
  return *_errors_tv;
}

//------------------------------------------------------------------------------
void ErrorsList::error_selected()
{
  Gtk::TreeModel::Path   path;
  Gtk::TreeView::Column *column(0);
  
  _errors_tv->get_cursor(path, column);

  Gtk::TreeModel::Row row = *(_errors_model->get_iter(path));

  const int         lineno = row[_errors_columns.lineno];
  const std::string msg    = row[_errors_columns.msg];
  _error_selected_signal.emit(lineno, msg);
}
