/////////////////////////////////////////////////////////////////////////////
// Name:        Utils.h
// Purpose:     Miscellaneous utilities
// Author:      Alex Thuering
// Created:		06.04.2008
// RCS-ID:      $Id: Utils.cpp,v 1.2 2008/07/13 19:28:02 ntalex Exp $
// Copyright:   (c) Alex Thuering
// Licence:     GPL
/////////////////////////////////////////////////////////////////////////////

#include "Utils.h"
#include <wx/clipbrd.h>
#include <wx/mstream.h>
#include <wx/log.h>
#include <wx/dataobj.h>

void CopyXmlToClipboard(wxSvgXmlNode* node, wxString dataFormatId) {
	wxMemoryOutputStream stream;
	wxSvgXmlDocument doc;
	doc.SetRoot(node);
	doc.Save(stream);
	int bufferSize = stream.GetSize();
	char* buffer = new char[bufferSize];
	stream.CopyTo(buffer, bufferSize);
	wxDataFormat format(dataFormatId);
	wxCustomDataObject* dataObj = new wxCustomDataObject(format);
	dataObj->TakeData(bufferSize, buffer);
	wxClipboardLocker locker;
	if (!locker)
		wxLogError(wxT("Can't open clipboard"));
	else if (!wxTheClipboard->SetData(dataObj))
		wxLogError(wxT("Can't copy xml node to the clipboard"));
}

bool GetXmlFromClipboard(wxString dataFormatId, wxSvgXmlDocument& doc) {
	if (!wxTheClipboard->Open()) {
		wxLogError(wxT("Can't open clipboard"));
		return false;
	}
	wxDataFormat format(dataFormatId);
	wxCustomDataObject dataObj(format);
	if (!wxTheClipboard->GetData(dataObj)) {
	  wxLogError(wxT("Can't paste data from the clipboard"));
	  wxTheClipboard->Close();
	  return false;
	}
	wxTheClipboard->Close();
	wxMemoryInputStream stream(dataObj.GetData(), dataObj.GetSize());
	if (!doc.Load(stream)) {
	  wxLogError(wxT("Can't paste object: error parsing"));
	  return false;
	}
	return true;
}

wxString GetTextFromClipboard() {
	if (!wxTheClipboard->Open()) {
		wxLogError(wxT("Can't open clipboard"));
		return wxT("");
	}
	wxTextDataObject textObj;
	if (!wxTheClipboard->GetData(textObj)) {
		wxLogError(wxT("Can't paste data from the clipboard"));
		wxTheClipboard->Close();
		return wxT("");
	}
	wxTheClipboard->Close();
	return textObj.GetText();
}
