#include "stdafx.h"

#include "grtdb/db_object_helpers.h"

#include "grts/structs.h"
#include "grts/structs.db.mgmt.h"
#include "grts/structs.db.mysql.h"

#include "grtpp.h"
#include "grt/grt_reporter.h"

using namespace grt;

#include "grti/sqlgenerator.h"
#include "grti/wbvalidation.h"

#include "db_mysql_validation_page.h"
#include "diff_tree.h"
#include "db_mysql_sql_export.h"

// copy-pasted from grt_manager.cpp
static std::string fmtstringlist(const StringListRef &strlist)
{
  std::string str;

  for (int i= 0; i < (int)strlist.count(); i++)
  {
    if (i == 0)
      str= strlist[i];
    else
    {
      std::string temp= strlist[i];
      str += "\n" + temp;
    }
  }
  return str;
}

DbMySQLValidationPage::DbMySQLValidationPage(bec::GRTManager *grtm)
  : _manager(grtm), messages_list(NULL)
{
}

void DbMySQLValidationPage::run_validation()
{
  bec::GRTTask *task= new bec::GRTTask("Catalog validation", 
    _manager->get_dispatcher(), 
    sigc::bind<grt::StringRef>(
      sigc::mem_fun(this, &DbMySQLSQLExport::validation_task), grt::StringRef()));

  task->signal_message().connect(sigc::mem_fun(this, &DbMySQLSQLExport::validation_message));
  task->signal_finished().connect(sigc::mem_fun(this, &DbMySQLSQLExport::validation_finished));
  _manager->get_dispatcher()->add_task(task);
}

void DbMySQLValidationPage::validation_finished(grt::ValueRef res)
{
  _validation_finished_cb();
}


void DbMySQLValidationPage::validation_message(const grt::Message &msg)
{
  switch (msg.type)
  {
  case grt::ErrorMsg:
  case grt::WarningMsg:
  case grt::InfoMsg:
  case grt::OutputMsg:
    messages_list.handle_message(msg);
    break;
    
  case grt::ProgressMsg:
    //XXX
    break;
  }
}


ValueRef DbMySQLValidationPage::validation_task(grt::GRT* grt, grt::StringRef)
{
  try
  {
    std::vector<WbValidationInterfaceWrapper*> validation_modules= grt->get_implementing_modules<WbValidationInterfaceWrapper>();
  
    if (validation_modules.empty())
      return grt::StringRef("\nSQL Script Export Error: Not able to locate 'Validation' modules");


    GrtObjectRef catalog(GrtObjectRef::cast_from(_manager->get_grt()->get("/wb/doc/physicalModels/0/catalog")));

    for (std::vector<WbValidationInterfaceWrapper*>::iterator module= validation_modules.begin();
         module != validation_modules.end(); ++module)
    {
      std::string caption= (*module)->getValidationDescription(catalog);
      
      if (!caption.empty())
      {
        grt->send_info("Starting "+caption);

        int validation_res= (*module)->validate("All", catalog);

        _manager->get_dispatcher()->call_from_main_thread<int>(
            sigc::bind(_validation_step_finished_cb, validation_res), true);
      }
    }
  }
  catch(std::exception& ex)
  {
    if (ex.what())
      return grt::StringRef(std::string("\nCatalog Validation Error: ").append(ex.what()).c_str());
    else
      return grt::StringRef("\nUnknown Catalog Validation Error");
  }

  return grt::StringRef("");
}
