/*
 * Tests locale handling
 *
 */
#include <coral/core/Element.h>
#include <coral/coral.h>
#include <coral/core/io/io.h>

#include <coral/core/python_compat.h>

#include <cmath>
#include <iostream>

int main() {
  int err = setenv("LC_ALL", "fi_FI", 1);
  coral_assert(err == 0);
  std::locale::global(std::locale(""));
  coral::init_coral_framework();
  coral::autounref<coral::Language> xmidi
    = coral::Language::__getLanguage__("XMIDI", 2, 0);
  coral::Atom* _m = xmidi->getElement("Point")->newAtom();
  coral::Element* m = static_cast<coral::Element*>(_m);
  m->__getSlotByName__("x")[0]->__setDValue__(3.41);
  m->__getSlotByName__("y")[0]->__setDValue__(4.31);
  coral::Set s;
  s.add(m);
  std::string xmi = coral::io::saveDocument_str(&s, "2.0");

  std::cout << "GOT THE FOLLOWING XMI:" << std::endl
	    << xmi << std::endl;

  std::string::size_type time_start = xmi.find("timestamp='");
  coral_assert(time_start != std::string::npos);
  time_start += 11;
  std::string::size_type time_end = xmi.find("00'>");
  coral_assert(time_end != std::string::npos);
  coral_assert(time_start < time_end);
  std::string t(xmi.begin() + time_start, xmi.begin() + time_end);
  std::cout << "Timestamp is " << t << std::endl;

  const char* weekdays[] = {"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"};
  std::string td(xmi.begin() + time_start, xmi.begin() + time_start + 3);
  bool ok = false;
  for (int i = 0; i < 7; ++i) {
    if (td == weekdays[i]) {
      ok = true;
      break;
    }
  }
  coral_assert(ok);

  std::string::size_type xpos = xmi.find(" x=\"3.4");
  coral_assert(xpos != std::string::npos);

  std::string::size_type ypos = xmi.find(" y=\"4.3");
  coral_assert(ypos != std::string::npos);

  const char* xmibuffer = xmi.c_str();
  coral::autounref<coral::Project> p(coral::io::loadDocument_str(xmibuffer));

  std::string inp = coral::io::saveDocument_str(p->contents(), "1.2");
  std::cout << "RE-LOADING RETURNED:" << std::endl << inp << std::endl;

  coral::ref_counted* r = p->contents()->__getitem__(0);;
  coral::Element* re = dynamic_cast<coral::Element*>(r);
  coral_assert(re);
  double cdx = re->__getSlotByName__("x")[0]->__getDValue__();
  double cdy = re->__getSlotByName__("y")[0]->__getDValue__();
  double epsilon = 0.011;
  coral_assert(std::fabs(cdx - 3.4) < epsilon);
  coral_assert(std::fabs(cdy - 4.3) < epsilon);
  return 0;
}
