/////////////////////////////////////////////////////////////////////////////
// Name:        Utils.h
// Purpose:     Miscellaneous utilities
// Author:      Alex Thuering
// Created:		06.04.2008
// RCS-ID:      $Id: Utils.cpp,v 1.3 2010/04/03 21:46:36 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();
}

int Sort(wxArrayString& keys, wxArrayString& values, const wxString& selectedKey) {
	int idx = -1;
	wxArrayString tmpArray;
	for (int i = 0; i<(int)keys.GetCount(); i++) {
		tmpArray.Add(values[i] + wxT("|") + keys[i]);
	}
	tmpArray.Sort();
	keys.Clear();
	values.Clear();
	for (int i = 0; i<(int)tmpArray.GetCount(); i++) {
		values.Add(tmpArray[i].BeforeLast('|'));
		wxString key = tmpArray[i].AfterLast('|');
		keys.Add(key);
		if (key == selectedKey)
			idx = keys.GetCount() - 1;
	}
	return idx;
}
