// Bug 661588 - ustring docs: the global locale should be set when using C++ streams

#include <memory>
#include <locale>
#include <sstream>
#include <iostream>
#include <string.h>
#include <locale.h>

#include <glibmm.h>
#include <gtkmm.h>

int main(int argc, char* argv[])
{
  int next_arg = 1;
  std::auto_ptr<Gtk::Main> p_gtk_main;
  if (argc > next_arg && strcmp(argv[next_arg], "--gtkinit") == 0)
  {
    next_arg++;
    p_gtk_main.reset(new Gtk::Main(argc, argv));
  }
  else
  {
    Glib::init();
  }

  if (argc > next_arg && strcmp(argv[next_arg], "--setlocale") == 0)
  {
    next_arg++;
    if (!setlocale(LC_ALL, "")) // Set the locale for C functions
    {
      std::cout << "setlocale: Could not set locale" << std::endl;
    }
  }

  if (argc > next_arg && strcmp(argv[next_arg], "--global") == 0)
  {
    next_arg++;
    try
    {
      // Set the global locale for C++ functions, and the locale for C functions
      std::locale::global(std::locale(""));
    }
    catch (const std::runtime_error& ex)
    {
      std::cout << "global, std::runtime_error: " << ex.what() << std::endl;
    }
  }

  std::ostringstream oss;

  if (argc > next_arg && strcmp(argv[next_arg], "--stream") == 0)
  {
    next_arg++;
    try
    {
      oss.imbue(std::locale("")); // Use the system locale for this stream
    }
    catch (const std::runtime_error& ex)
    {
      std::cout << "stream, std::runtime_error: " << ex.what() << std::endl;
    }
  }
  if (argc > next_arg)
  {
    std::cout << "Unknown argument: " << argv[next_arg] << std::endl;
    std::cout << "Usage: " << argv[0]
              << " [--gtkinit] [--setlocale] [--global] [--stream]" << std::endl;
    return 2;
  }

  const char* locale_charset;
  const gboolean locale_utf8 = g_get_charset(&locale_charset);
  std::cout << "Locale encoding: UTF-8=" << locale_utf8 << ", " << locale_charset << std::endl;

  try
  {
    Glib::ustring str("ó ");
    float num = 1234.56;
    oss << str << num;
  }
  catch(const Glib::ConvertError& ex)
  {
    std::cout << "ConvertError: " << ex.what() << std::endl;
    return 1;
  }
  std::cout << "No ConvertError: " << oss.str() << std::endl;
  return 0;
}

