
#include "stdafx.h"

#include "grtpp_module_cpp.h"
#include <mforms/mforms.h>
#include <mforms/simpleform.h>


#include <grt/grt_manager.h>

#define Forms_VERSION "1.0.0"

class FormsImpl : public grt::ModuleImplBase
{
public:
  FormsImpl(grt::CPPModuleLoader *ldr) : grt::ModuleImplBase(ldr) {}

  DEFINE_INIT_MODULE(Forms_VERSION, "Sun Microsystems Inc.", grt::ModuleImplBase,
                  DECLARE_MODULE_FUNCTION(FormsImpl::show_simple_form),
  NULL);
  //                DECLARE_MODULE_FUNCTION(FormsImpl::test_wizard), NULL);

  int show_simple_form(const std::string &title, const std::string &definition, grt::DictRef results);

  int test_wizard();

private:
  int show_simple_form_main(const std::string &title, const std::string &definition,
    grt::DictRef result);
};

GRT_MODULE_ENTRY_POINT(FormsImpl);

using namespace mforms;

/*
int FormsImpl::test_wizard() // test
{
#ifdef _WIN32
  extern void __declspec(dllimport) wiztest();
#else
  extern void wiztest();
#endif

  bec::GRTManager::get_instance_for(get_grt())->get_dispatcher()->
    call_from_main_thread<void>(
    sigc::ptr_fun(wiztest), true);

  return 0;
}*/


int FormsImpl::show_simple_form(const std::string &title, const std::string &definition,
    grt::DictRef result)
{
  return bec::GRTManager::get_instance_for(get_grt())->get_dispatcher()->
    call_from_main_thread<int>(sigc::bind<std::string,std::string,grt::DictRef>(
        sigc::mem_fun(this,&FormsImpl::show_simple_form_main),title,definition,result), true);
}


int FormsImpl::show_simple_form_main(const std::string &title, const std::string &definition,
    grt::DictRef result)
{
  SimpleForm sform(title, "OK");

  sform.parse_definition(definition);

  bool ok= sform.show();

  if (ok)
  {
    std::map<std::string,Control*> controls(sform.get_controls());

    if (result.is_valid())
    {
      for (std::map<std::string,Control*>::const_iterator iter= controls.begin(); 
        iter != controls.end(); ++iter)
      {
        if (dynamic_cast<CheckBox*>(iter->second))
          result.gset(iter->first, iter->second->get_bool_value());
        else
          result.gset(iter->first, iter->second->get_string_value());
      }
    }
    return 1;
  }

  return 0;
}
