#include "stdafx.h"

#include "wb_editor_storednote.h"
#include "grts/structs.workbench.physical.h"
#include "grt/exceptions.h"


StoredNoteEditorBE::StoredNoteEditorBE(bec::GRTManager *grtm, const GrtStoredNoteRef &note)
: bec::BaseEditor(grtm, note), _note(note)
{
}


bool StoredNoteEditorBE::is_script()
{
  return _note.is_instance(db_Script::static_class_name());
}


Sql_editor * StoredNoteEditorBE::get_sql_editor()
{
  if (!_sql_editor.get())
  {
    workbench_physical_ModelRef model(workbench_physical_ModelRef::cast_from(_note->owner()));
    _sql_editor= Sql_editor::create_sql_editor(model->rdbms());
  }
  return _sql_editor.get();
}


void StoredNoteEditorBE::set_text(const std::string &text)
{  
  bool flag;
  if (get_text(flag) != text)
  {
    //XXX replace this using module wrapper class
    grt::Module *module= get_grt()->get_module("Workbench");
    if (!module)
      throw std::runtime_error("Workbench module not found");
    
    grt::BaseListRef args(get_grt());
    
    args.ginsert(_note->filename());
    args.ginsert(grt::StringRef(text));
    
    module->call_function("setAttachedFileContents", args);
    
    _note->lastChangeDate(bec::fmttime(0, DATETIME_FMT));
  }
}


std::string StoredNoteEditorBE::get_text(bool &isutf8)
{
  //XXX replace this using module wrapper class
  grt::Module *module= get_grt()->get_module("Workbench");
  if (!module)
    throw std::runtime_error("Workbench module not found");

  grt::BaseListRef args(get_grt());

  args.ginsert(_note->filename());

  grt::StringRef value(grt::StringRef::cast_from(module->call_function("getAttachedFileContents", args)));

  if (!g_utf8_validate(value.c_str(), strlen(value.c_str()), NULL))
  {
    isutf8= false;
    return "";
  }
  isutf8= true;

  return *value;
}


void StoredNoteEditorBE::set_name(const std::string &name)
{
  if (_note->name() != name)
  {
    workbench_physical_ModelRef model(workbench_physical_ModelRef::cast_from(_note->owner()));
    
    if (!model.is_valid())
      throw std::logic_error("Note owner not set");
    
    grt::ListRef<GrtStoredNote> notes(model->notes());
    for (size_t c= notes.count(), i= 0; i < c; i++)
    {
      GrtStoredNoteRef note(notes[i]);
      
      if (note != _note && *note->name() == name)
        throw bec::validation_error(_("Duplicate note name."));
    }
    
    bec::AutoUndoEdit undo(this, _note, "name");
    _note->name(name);
    undo.end(strfmt(_("Rename '%s' to '%s'"), _note->name().c_str(), name.c_str()));
  }
}


std::string StoredNoteEditorBE::get_name()
{
  return _note->name();
}


bool StoredNoteEditorBE::load_file(const std::string &name)
{
  gchar *contents;
  gsize length;

  if (g_file_get_contents(name.c_str(), &contents, &length, NULL))
  {
    gchar *end= NULL;

    if (!g_utf8_validate(contents, length, (const gchar**)&end))
    {
      gchar *data;
      glong iread, iwritten;
      bool ok= false;

      // check if utf16
      if (length >= 2 && (guchar)contents[0] == 0xff && (guchar)contents[1] == 0xfe)
      {
        data= g_utf16_to_utf8((const gunichar2*)contents, length, &iread, &iwritten, NULL);
        if (data)
        {
          get_grt()->send_info(strfmt(_("Attached file '%s' has been converted from UTF-16 to UTF-8."), name.c_str()));
          g_free(contents);
          contents= data;
          length= iwritten;
          ok= true;
        }
      }
      
      if (!ok)
        throw std::runtime_error(strfmt(_("File '%s' contains invalid UTF-8 data."), name.c_str()));
    }
    else
      *end= 0;

    set_text(std::string(contents, length));
    g_free(contents);
    return true;
  }
  return false;
}


bool StoredNoteEditorBE::save_file(const std::string &name)
{
   grt::Module *module= get_grt()->get_module("Workbench");
  if (!module)
    throw std::runtime_error("Workbench module not found");

  grt::BaseListRef args(get_grt());

  args.ginsert(_note->filename());
  args.ginsert(grt::StringRef(name));

  grt::IntegerRef value(grt::IntegerRef::cast_from(module->call_function("exportAttachedFileContents", args)));

  return *value == 0;
}

