/* 
 * Copyright (c) 2009, 2011, Oracle and/or its affiliates. All rights reserved.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; version 2 of the
 * License.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301  USA
 */


#include "stdafx.h"

#include "grtpp_module_cpp.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>(
    std::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>(boost::bind(&FormsImpl::show_simple_form_main,this,title,definition,result), true, false);
}


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, View*> views(sform.get_views());

    if (result.is_valid())
    {
      for (std::map<std::string, View*>::const_iterator iter= views.begin(); 
        iter != views.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;
}
