/* 
 * Copyright (c) 2009, 2010, 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 "wb_editor_storednote.h"
#include "grts/structs.workbench.physical.h"
#include "grt/exceptions.h"
#include "grtui/file_charset_dialog.h"
#include "base/string_utilities.h"

using namespace base;

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::Ref StoredNoteEditorBE::get_sql_editor()
{
  if (!_sql_editor)
  {
    workbench_physical_ModelRef model(workbench_physical_ModelRef::cast_from(_note->owner()));
    _sql_editor= Sql_editor::create(model->rdbms());
  }
  return _sql_editor;
}


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))
  {
    std::string converted;
    
    if (FileCharsetDialog::ensure_filedata_utf8(contents, length, "",
                                                name, 
                                                converted))
    {
      set_text(converted);
      g_free(contents);
      return true;
    }
    g_free(contents);
  }
  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;
}

