/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 * 
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_connectivity.hxx"
#include "hsqldb/HStorageAccess.hxx"
#include <comphelper/processfactory.hxx>
#include <com/sun/star/embed/XStorage.hpp>
#include <com/sun/star/embed/ElementModes.hpp>
#include <com/sun/star/io/XStream.hpp>
#include "hsqldb/HStorageMap.hxx"
#include "hsqldb/StorageNativeInputStream.h"
#include "accesslog.hxx"
#include "diagnose_ex.h"

#include <string.h>

using namespace ::com::sun::star::container;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::embed;
using namespace ::com::sun::star::io;
using namespace ::com::sun::star::lang;
using namespace ::connectivity::hsqldb;

#define OUSTR(x) ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(x) )
#define ThrowException(env, type, msg) { \
	env->ThrowNew(env->FindClass(type), msg); }

/*
 * Class:     com_sun_star_sdbcx_comp_hsqldb_NativeStorageAccess
 * Method:    openStream
 * Signature: (Ljava/lang/String;Ljava/lang/String;I)V
 */
SAL_DLLPUBLIC_EXPORT void JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_NativeStorageAccess_openStream
  (JNIEnv * env, jobject /*obj_this*/,jstring name, jstring key, jint mode)
{
#ifdef HSQLDB_DBG
    {
        OperationLogFile( env, name, "data" ).logOperation( "openStream" );
        LogFile( env, name, "data" ).create();
    }
#endif

	StorageContainer::registerStream(env,name,key,mode);
}
// -----------------------------------------------------------------------------
/*
 * Class:     com_sun_star_sdbcx_comp_hsqldb_NativeStorageAccess
 * Method:    close
 * Signature: (Ljava/lang/String;Ljava/lang/String;)V
 */
SAL_DLLPUBLIC_EXPORT void JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_NativeStorageAccess_close
  (JNIEnv * env, jobject /*obj_this*/,jstring name, jstring key)
{
#ifdef HSQLDB_DBG
	{
		::rtl::OUString sKey = StorageContainer::jstring2ustring(env,key);
		::rtl::OUString sName = StorageContainer::jstring2ustring(env,name);
	}
#endif
    ::boost::shared_ptr<StreamHelper> pHelper = StorageContainer::getRegisteredStream(env,name,key);
    Reference< XOutputStream> xFlush = pHelper.get() ? pHelper->getOutputStream() : Reference< XOutputStream>();
    if ( xFlush.is() )
        try
        {
            xFlush->flush();
        }
        catch(Exception&)
        {
            OSL_ENSURE( false, "NativeStorageAccess::close: caught an exception while flushing!" );
        }
#ifdef HSQLDB_DBG
    {
        OperationLogFile aOpLog( env, name, "data" );
        aOpLog.logOperation( "close" );
        aOpLog.close();

        LogFile aDataLog( env, name, "data" );
        aDataLog.close();
    }
#endif

	StorageContainer::revokeStream(env,name,key);
}
// -----------------------------------------------------------------------------
/*
 * Class:     com_sun_star_sdbcx_comp_hsqldb_NativeStorageAccess
 * Method:    getFilePointer
 * Signature: (Ljava/lang/String;Ljava/lang/String;)J
 */
SAL_DLLPUBLIC_EXPORT jlong JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_NativeStorageAccess_getFilePointer
  (JNIEnv * env, jobject /*obj_this*/,jstring name, jstring key)
{
#ifdef HSQLDB_DBG
    OperationLogFile aOpLog( env, name, "data" );
    aOpLog.logOperation( "getFilePointer" );
#endif

    ::boost::shared_ptr<StreamHelper> pHelper = StorageContainer::getRegisteredStream(env,name,key);
	OSL_ENSURE(pHelper.get(),"No stream helper!");

    jlong nReturn = pHelper.get() ? pHelper->getSeek()->getPosition() : jlong(0);
#ifdef HSQLDB_DBG
    aOpLog.logReturn( nReturn );
#endif
    return nReturn;
}
// -----------------------------------------------------------------------------

/*
 * Class:     com_sun_star_sdbcx_comp_hsqldb_NativeStorageAccess
 * Method:    length
 * Signature: (Ljava/lang/String;Ljava/lang/String;)J
 */
SAL_DLLPUBLIC_EXPORT jlong JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_NativeStorageAccess_length
  (JNIEnv * env, jobject /*obj_this*/,jstring name, jstring key)
{
#ifdef HSQLDB_DBG
    OperationLogFile aOpLog( env, name, "data" );
    aOpLog.logOperation( "length" );
#endif

    ::boost::shared_ptr<StreamHelper> pHelper = StorageContainer::getRegisteredStream(env,name,key);
	OSL_ENSURE(pHelper.get(),"No stream helper!");

    jlong nReturn = pHelper.get() ? pHelper->getSeek()->getLength() :jlong(0);
#ifdef HSQLDB_DBG
    aOpLog.logReturn( nReturn );
#endif
    return nReturn;
}

// -----------------------------------------------------------------------------

jint read_from_storage_stream( JNIEnv * env, jobject /*obj_this*/, jstring name, jstring key, DataLogFile* logger )
{
    OSL_UNUSED( logger );
	::boost::shared_ptr<StreamHelper> pHelper = StorageContainer::getRegisteredStream(env,name,key);
    Reference< XInputStream> xIn = pHelper.get() ? pHelper->getInputStream() : Reference< XInputStream>();
	OSL_ENSURE(xIn.is(),"Input stream is NULL!");
	if ( xIn.is() )
	{
		Sequence< ::sal_Int8 > aData(1);
        sal_Int32 nBytesRead = -1;
        try
        {
		    nBytesRead = xIn->readBytes(aData,1);
        }
        catch(Exception& e)
	    {
            StorageContainer::throwJavaException(e,env);
            return -1;

	    }
		if (nBytesRead <= 0)
        {
			return (-1);
		}
        else
        {
			sal_Int32 tmpInt = aData[0];
			if (tmpInt < 0 )
				tmpInt = 256 +tmpInt;

#ifdef HSQLDB_DBG
            if ( logger )
                logger->write( tmpInt );
#endif
			return(tmpInt);
		}
	}
	return -1;
}

// -----------------------------------------------------------------------------

/*
 * Class:     com_sun_star_sdbcx_comp_hsqldb_NativeStorageAccess
 * Method:    read
 * Signature: (Ljava/lang/String;Ljava/lang/String;)I
 */
SAL_DLLPUBLIC_EXPORT jint JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_NativeStorageAccess_read__Ljava_lang_String_2Ljava_lang_String_2
  (JNIEnv* env, jobject obj_this, jstring name, jstring key)
{
#ifdef HSQLDB_DBG
    OperationLogFile aOpLog( env, name, "data" );
    aOpLog.logOperation( "read" );

    DataLogFile aDataLog( env, name, "data" );
    return read_from_storage_stream( env, obj_this, name, key, &aDataLog );
#else
    return read_from_storage_stream( env, obj_this, name, key );
#endif
}

// -----------------------------------------------------------------------------

jint read_from_storage_stream_into_buffer( JNIEnv * env, jobject /*obj_this*/,jstring name, jstring key, jbyteArray buffer, jint off, jint len, DataLogFile* logger )
{
    OSL_UNUSED( logger );
#ifdef HSQLDB_DBG
	{
		::rtl::OUString sKey = StorageContainer::jstring2ustring(env,key);
		::rtl::OUString sName = StorageContainer::jstring2ustring(env,name);
	}
#endif
	::boost::shared_ptr<StreamHelper> pHelper = StorageContainer::getRegisteredStream(env,name,key);
	Reference< XInputStream> xIn = pHelper.get() ? pHelper->getInputStream() : Reference< XInputStream>();
	OSL_ENSURE(xIn.is(),"Input stream is NULL!");
	if ( xIn.is() )
	{
		jsize nLen = env->GetArrayLength(buffer);
        if ( nLen < len || len <= 0 )
        {
            ThrowException(	env,
					"java/io/IOException",
					"len is greater or equal to the buffer size");
	        return -1;
        }
		sal_Int32 nBytesRead = -1;

        Sequence< ::sal_Int8 > aData(nLen);
        try
        {
            nBytesRead = xIn->readBytes(aData, len);
        }
        catch(Exception& e)
        {
            StorageContainer::throwJavaException(e,env);
            return -1;
        }

        if (nBytesRead <= 0)
            return -1;
        env->SetByteArrayRegion(buffer,off,nBytesRead,&aData[0]);

#ifdef HSQLDB_DBG
        if ( logger )
            logger->write( aData.getConstArray(), nBytesRead );
#endif
	    return nBytesRead;
	}
	ThrowException(	env,
					"java/io/IOException",
					"Stream is not valid");
	return -1;
}
// -----------------------------------------------------------------------------

/*
 * Class:     com_sun_star_sdbcx_comp_hsqldb_NativeStorageAccess
 * Method:    read
 * Signature: (Ljava/lang/String;Ljava/lang/String;[BII)I
 */
SAL_DLLPUBLIC_EXPORT jint JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_NativeStorageAccess_read__Ljava_lang_String_2Ljava_lang_String_2_3BII
  (JNIEnv * env, jobject obj_this,jstring name, jstring key, jbyteArray buffer, jint off, jint len)
{
#ifdef HSQLDB_DBG
    OperationLogFile aOpLog( env, name, "data" );
    aOpLog.logOperation( "read( byte[], int, int )" );

    DataLogFile aDataLog( env, name, "data" );
    return read_from_storage_stream_into_buffer( env, obj_this, name, key, buffer, off, len, &aDataLog );
#else
    return read_from_storage_stream_into_buffer( env, obj_this, name, key, buffer, off, len );
#endif
}

// -----------------------------------------------------------------------------

/*
 * Class:     com_sun_star_sdbcx_comp_hsqldb_NativeStorageAccess
 * Method:    readInt
 * Signature: (Ljava/lang/String;Ljava/lang/String;)I
 */
SAL_DLLPUBLIC_EXPORT jint JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_NativeStorageAccess_readInt
  (JNIEnv * env, jobject /*obj_this*/,jstring name, jstring key)
{
#ifdef HSQLDB_DBG
    OperationLogFile aOpLog( env, name, "data" );
    aOpLog.logOperation( "readInt" );
#endif

	::boost::shared_ptr<StreamHelper> pHelper = StorageContainer::getRegisteredStream(env,name,key);
	Reference< XInputStream> xIn = pHelper.get() ? pHelper->getInputStream() : Reference< XInputStream>();
	OSL_ENSURE(xIn.is(),"Input stream is NULL!");
	if ( xIn.is() )
    {
        Sequence< ::sal_Int8 > aData(4);
        sal_Int32 nBytesRead = -1;
        try
        {
            nBytesRead = xIn->readBytes(aData, 4);
        }
        catch(Exception& e)
        {
            StorageContainer::throwJavaException(e,env);
            return -1;
        }

        if ( nBytesRead != 4 ) {
            ThrowException( env,
                            "java/io/IOException",
                            "Bytes read != 4");
            return -1;
        }

        Sequence< sal_Int32 > ch(4);
        for(sal_Int32 i = 0;i < 4; ++i)
        {
            ch[i] = aData[i];
            if (ch[i] < 0 )
                ch[i] = 256 + ch[i];
        }

        if ((ch[0] | ch[1] | ch[2] | ch[3]) < 0)
        {
            ThrowException( env,
                            "java/io/IOException",
                            "One byte is < 0");
            return -1;
        }
        jint nRet = ((ch[0] << 24) + (ch[1] << 16) + (ch[2] << 8) + (ch[3] << 0));
#ifdef HSQLDB_DBG
        DataLogFile aDataLog( env, name, "data" );
        aDataLog.write( nRet );

        aOpLog.logReturn( nRet );
#endif
		return nRet;
	}
	ThrowException(	env,
					"java/io/IOException",
					"No InputStream");
	return -1;
}
// -----------------------------------------------------------------------------

/*
 * Class:     com_sun_star_sdbcx_comp_hsqldb_NativeStorageAccess
 * Method:    seek
 * Signature: (Ljava/lang/String;Ljava/lang/String;J)V
 */
SAL_DLLPUBLIC_EXPORT void JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_NativeStorageAccess_seek
  (JNIEnv * env, jobject /*obj_this*/,jstring name, jstring key, jlong position)
{
#ifdef HSQLDB_DBG
    OperationLogFile aOpLog( env, name, "data" );
    aOpLog.logOperation( "seek", position );
#endif

    ::boost::shared_ptr<StreamHelper> pHelper = StorageContainer::getRegisteredStream(env,name,key);
	Reference< XSeekable> xSeek = pHelper.get() ? pHelper->getSeek() : Reference< XSeekable>();

	OSL_ENSURE(xSeek.is(),"No Seekable stream!");
	if ( xSeek.is() )
	{
    #ifdef HSQLDB_DBG
        DataLogFile aDataLog( env, name, "data" );
    #endif

		::sal_Int64 nLen = xSeek->getLength();
		if ( nLen < position)
		{
			static ::sal_Int64 BUFFER_SIZE = 9192;
        #ifdef HSQLDB_DBG
            aDataLog.seek( nLen );
        #endif
			xSeek->seek(nLen);
			Reference< XOutputStream> xOut = pHelper->getOutputStream();
			OSL_ENSURE(xOut.is(),"No output stream!");

			::sal_Int64 diff = position - nLen;
			sal_Int32 n;
			while( diff != 0 )
			{
				if ( BUFFER_SIZE < diff )
				{
					n = static_cast<sal_Int32>(BUFFER_SIZE);
					diff = diff - BUFFER_SIZE;
				}
				else
				{
					n = static_cast<sal_Int32>(diff);
					diff = 0;
				}
				Sequence< ::sal_Int8 > aData(n);
				memset(aData.getArray(),0,n);
				xOut->writeBytes(aData);
            #ifdef HSQLDB_DBG
                aDataLog.write( aData.getConstArray(), n );
            #endif
			}
		}
        xSeek->seek(position);
        OSL_ENSURE(xSeek->getPosition() == position,"Wrong position after seeking the stream");

    #ifdef HSQLDB_DBG
        aDataLog.seek( position );
        OSL_ENSURE( xSeek->getPosition() == aDataLog.tell(), "Wrong position after seeking the stream" );
    #endif
	}
}
// -----------------------------------------------------------------------------

void write_to_storage_stream_from_buffer( JNIEnv* env, jobject /*obj_this*/, jstring name, jstring key, jbyteArray buffer, jint off, jint len, DataLogFile* logger )
{
    OSL_UNUSED( logger );
    ::boost::shared_ptr<StreamHelper> pHelper = StorageContainer::getRegisteredStream(env,name,key);
	Reference< XOutputStream> xOut = pHelper.get() ? pHelper->getOutputStream() : Reference< XOutputStream>();
	OSL_ENSURE(xOut.is(),"Stream is NULL");

	try
	{
		if ( xOut.is() )
		{
			jbyte *buf = env->GetByteArrayElements(buffer,NULL);
			if (JNI_FALSE != env->ExceptionCheck())
            {
                env->ExceptionClear();
				OSL_ENSURE(0,"ExceptionClear");
            }
			OSL_ENSURE(buf,"buf is NULL");
			if ( buf && len > 0 && len <= env->GetArrayLength(buffer))
			{
				Sequence< ::sal_Int8 > aData(buf + off,len);
                env->ReleaseByteArrayElements(buffer, buf, JNI_ABORT);
				xOut->writeBytes(aData);				
#ifdef HSQLDB_DBG
                if ( logger )
                    logger->write( aData.getConstArray(), len );
#endif
			}
		}
		else
		{
			ThrowException(	env,
					"java/io/IOException",
					"No OutputStream");
		}
	}
	catch(Exception& e)
	{
		OSL_ENSURE(0,"Exception caught! : write [BII)V");
        StorageContainer::throwJavaException(e,env);
	}
}

// -----------------------------------------------------------------------------

/*
 * Class:     com_sun_star_sdbcx_comp_hsqldb_NativeStorageAccess
 * Method:    write
 * Signature: (Ljava/lang/String;Ljava/lang/String;[BII)V
 */
SAL_DLLPUBLIC_EXPORT void JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_NativeStorageAccess_write
  (JNIEnv * env, jobject obj_this,jstring name, jstring key, jbyteArray buffer, jint off, jint len)
{
#ifdef HSQLDB_DBG
    OperationLogFile aOpLog( env, name, "data" );
    aOpLog.logOperation( "write( byte[], int, int )" );

    DataLogFile aDataLog( env, name, "data" );
    write_to_storage_stream_from_buffer( env, obj_this, name, key, buffer, off, len, &aDataLog );
#else
    write_to_storage_stream_from_buffer( env, obj_this, name, key, buffer, off, len );
#endif
}
// -----------------------------------------------------------------------------

void write_to_storage_stream( JNIEnv* env, jobject /*obj_this*/, jstring name, jstring key, jint v, DataLogFile* logger )
{
    OSL_UNUSED( logger );

	::boost::shared_ptr<StreamHelper> pHelper = StorageContainer::getRegisteredStream(env,name,key);
	Reference< XOutputStream> xOut = pHelper.get() ? pHelper->getOutputStream() : Reference< XOutputStream>();
	OSL_ENSURE(xOut.is(),"Stream is NULL");
	try
	{
		if ( xOut.is() )
		{
			Sequence< ::sal_Int8 > oneByte(4);
			oneByte[0] = (sal_Int8) ((v >> 24) & 0xFF);
			oneByte[1] = (sal_Int8) ((v >> 16) & 0xFF);
			oneByte[2] = (sal_Int8) ((v >>  8) & 0xFF);
			oneByte[3] = (sal_Int8) ((v >>  0) & 0xFF);

			xOut->writeBytes(oneByte);
#ifdef HSQLDB_DBG
            if ( logger )
                logger->write( oneByte.getConstArray(), 4 );
#endif
		}
		else
		{
			ThrowException(	env,
					"java/io/IOException",
					"No OutputStream");
		}
	}
	catch(Exception& e)
	{
		OSL_ENSURE(0,"Exception catched! : writeBytes(aData);");
        StorageContainer::throwJavaException(e,env);
	}
}

// -----------------------------------------------------------------------------

/*
 * Class:     com_sun_star_sdbcx_comp_hsqldb_NativeStorageAccess
 * Method:    writeInt
 * Signature: (Ljava/lang/String;Ljava/lang/String;I)V
 */
SAL_DLLPUBLIC_EXPORT void JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_NativeStorageAccess_writeInt
  (JNIEnv * env, jobject obj_this,jstring name, jstring key, jint v)
{
#ifdef HSQLDB_DBG
    OperationLogFile aOpLog( env, name, "data" );
    aOpLog.logOperation( "writeInt" );

    DataLogFile aDataLog( env, name, "data" );
    write_to_storage_stream( env, obj_this, name, key, v, &aDataLog );
#else
    write_to_storage_stream( env, obj_this, name, key, v );
#endif
}