/*
 *    MGPPRetrieveWrapperImpl.c
 *    Copyright (C) 2007 New Zealand Digital Library, http://www.nzdl.org
 *
 *    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; either version 2 of the License, or
 *    (at your option) any later version.
 *
 *    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., 675 Mass Ave, Cambridge, MA 02139, USA.
 */ 

#ifdef __WIN32__
#include <win32cfg.h>
#endif

#include <jni.h>

#ifdef __MINGW32__

/* Cross compiling for Windows
   Want the type definitions in *win32* version of jni_md.h but
   this then leads to C-mangled style functions which we *don't*
   want.  The following achieves this */

#undef JNIEXPORT
#undef JNIIMPORT
#undef JNICALL

#define JNIEXPORT
#define JNIIMPORT
#define JNICALL
#endif

#include "org_greenstone_mgpp_MGPPRetrieveWrapper.h"
#include "TextGet.h"


//****************************************************
// retrieve a document
//****************************************************

/* returns a document from mgpp as a string
Note: TextData isn't cached - just reloaded each time
*/
JNIEXPORT jstring JNICALL 
Java_org_greenstone_mgpp_MGPPRetrieveWrapper_getDocument (JNIEnv *j_env, 
 jobject j_obj, jstring j_text_name, jstring j_level, jlong j_docnum) {
  
#ifdef __WIN32__
  const char* base_dir = "";
#else
  const char* base_dir = "/";
#endif

  const char * text_name = j_env->GetStringUTFChars(j_text_name, NULL);
  if (text_name==NULL) {
   return NULL;
  }

  const char * level = j_env->GetStringUTFChars( j_level, NULL);
  if (level==NULL) {
   j_env->ReleaseStringUTFChars(j_text_name, text_name);
   return NULL;
  }
    
  // does this work alright? j_docnum is a long (64 bit)
  mg_u_long docnum = j_docnum;
  TextData td;

  // cast to char* otherwise complains about const
  td.LoadData((char *)base_dir, (char *)text_name);

  UCArray mg_level;
  SetCStr(mg_level, level);
  UCArray docText;
  docText.clear();
  // get the actual text
  if (!GetDocText(td, mg_level, docnum, docText)) {
    cerr <<"MGPP JNI: couldn't retrieve doc text"<<endl;
  }

  td.UnloadData();
  
  char * doc = GetCStr(docText); 
  jstring result = j_env->NewStringUTF(doc);
  // release any gets
  j_env->ReleaseStringUTFChars(j_text_name, text_name);
  j_env->ReleaseStringUTFChars(j_level, level);

  // free any C++ stuff
  delete doc;

  return result;
 
}
