/**
 * volser.cpp : Version 1.2 jni methods in nativevolser.dll
 * For instructions on using javah and the C/C++ compiles see:
 * http://mindprod.com/jgloss/jni.html#COMPILING
 *
 * Copyright: (c) 2007-2017 Roedy Green, Canadian Mind Products
 */
#define UNICODE
#define _UNICODE

#include <Windows.h>
#include <WinBase.h>
#include <String.h>

// JNI prototypes generated by javah
#include "volser.h"

/*
 * Class:     com_mindprod_volser_Volser
 * Method:    getVolser
 * Signature: (Ljava/lang/String;)Ljava/lang/String;
 */
JNIEXPORT jint JNICALL Java_com_mindprod_volser_Volser_getVolser
   (JNIEnv * env, jclass volserClass, jstring rootPathName)
   {
   // 16-bit char RootPathName without terminating null, e.g. "C:\"
   const wchar_t * lpRootPathName16 = ( wchar_t *)  env->GetStringChars( rootPathName, NULL /* don't need copy notification */ );
   if ( lpRootPathName16 == NULL )
      {
      return 0;
      }
   jsize rootLen = env->GetStringLength( rootPathName );

   // 16-bit char RootPathName with terminating null
   wchar_t * lpRootPathName16_0 = new wchar_t[ rootLen+1 ];

   // copy to apply trailing null
   errno_t err = wcsncpy_s(
                          lpRootPathName16_0 /* dest */,
                          rootLen+1 /* dest length */,
                          lpRootPathName16 /* src */,
                          rootLen /* chars to copy */
                          );

   // no longer need handle to Java string, since we have a copy.
   env->ReleaseStringChars( rootPathName, (const jchar *) lpRootPathName16 );

   if ( err )
      {
      delete[] lpRootPathName16_0;
      return 0;
      }

   LPTSTR lpVolumeNameBuffer = new TCHAR[ MAX_PATH+1 ];

   DWORD volumeSerialNumber;

   BOOL ok = GetVolumeInformation(
                                 (LPCTSTR)lpRootPathName16_0,
                                 lpVolumeNameBuffer,
                                 MAX_PATH+1 /* nVolumeNameSize */,
                                 &volumeSerialNumber,
                                 NULL /*lpMaximumComponentLength */,
                                 NULL /* lpFileSystemFlags */,
                                 NULL /* lpFileSystemNameBuffer */,
                                 0 /* nFileSystemNameSize */
                                 );

   delete[] lpRootPathName16_0;
   delete[] lpVolumeNameBuffer;

   return ok ? volumeSerialNumber : 0 ;
   }

// not class, so no final }