/*----------------------------------------------------------------------------*/
/*!
Copyright (c) 2018, 2019 by Christian Nowak a.k.a. Creestee a.k.a. chn
Contact: chnowak@web.de or creestee@creestee.com
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. This application may be used and redistributed in source code and binary
form free of charge for personal and for educational purposes.
4. Redistribution and usage of this application in source code or binary form
for commercial purposes requires explicit written permission from the
author.


THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the RadarVolumeExplorer project.
*/
/*----------------------------------------------------------------------------*/

#include "RveHDF5Compound.h"
#include <QImage>
#include <QtGlobal>

#include <stdlib.h>
#include <iostream>

/*----------------------------------------------------------------------------*/
/*!
*/
/*----------------------------------------------------------------------------*/
RveHDF5Compound::RveHDF5Compound( QString name, void *data, size_t nItems, size_t itemSize )
{
   m_Name = name;
   m_NumItems = nItems;
   m_ItemSize = itemSize;
   m_pData = malloc( m_NumItems * m_ItemSize );
   memcpy( m_pData, data, m_NumItems * m_ItemSize );
}


RveHDF5Compound::RveHDF5Compound( QString name, hid_t dataset, RveHDF5Object *parent )
{
   m_Name = name;
   m_pParent = parent;
   load( dataset );
}

/*----------------------------------------------------------------------------*/
/*!
   Destructor
*/
/*----------------------------------------------------------------------------*/
RveHDF5Compound::~RveHDF5Compound()
{
   free( m_pData );
}


/*----------------------------------------------------------------------------*/
/*!
   Retrieve the data type of the dataset
   \return the datatype
*/
/*----------------------------------------------------------------------------*/
RveHDF5Attribute::ATTR_TYPE RveHDF5Compound::dataType()
{
   return( RveHDF5Attribute::ATTR_COMPOUND );
}


/*----------------------------------------------------------------------------*/
/*!
   Load the data from a dataset object in an HDF5 file
   \param dset handle of the hdf5 dataset object
   \return true on success
*/
/*----------------------------------------------------------------------------*/
bool RveHDF5Compound::load( hid_t dset )
{
   m_CompoundTypes.clear();
   // ******** CN: ToDo
   hid_t space;
   void *rdata;                     /* Read buffer */

   // Get dataspace and allocate memory for read buffer.
   hid_t type = H5Dget_type( dset );
   size_t typeSize = H5Tget_size( type );
   space = H5Dget_space( dset );
   int rank = H5Sget_simple_extent_ndims( space );

   H5O_info_t oinfo;
   H5Oget_info( dset, &oinfo );
   int nMembers = H5Tget_nmembers( type );
   for( int i = 0; i < nMembers; i++ )
   {
      QString memberName = QString( H5Tget_member_name( type, i ) );
      size_t memberOffset = H5Tget_member_offset( type, i );
      hid_t memberType = H5Tget_member_type( type, i );
      size_t memberSize = H5Tget_size( memberType );
      RveHDF5Attribute::ATTR_TYPE at;
      switch( H5Tget_class( memberType ) )
      {
         case H5T_FLOAT:
            at = RveHDF5Attribute::ATTR_FLOAT;
            break;
         case H5T_INTEGER:
            at = RveHDF5Attribute::ATTR_INTEGER;
            break;
         default:
            at = RveHDF5Attribute::ATTR_NONE;
      }
      addCompoundType( memberName, at, memberOffset, memberSize );
   }
   hsize_t *dims = new hsize_t[ rank ];
   H5Sget_simple_extent_dims( space, dims, 0 );

   rdata = malloc( dims[0] * typeSize );
//   memtype = H5Tcreate( H5T_COMPOUND, sizeof( typeSize ) );
   H5Dread( dset, type, H5S_ALL, H5S_ALL, H5P_DEFAULT, rdata );

   m_NumItems = dims[0];
   m_ItemSize = typeSize;
   m_pData = rdata;

   return( true );
}


QVariant RveHDF5Compound::data( const QString &name, int n ) const
{
   if( n >= m_NumItems )
      return( 0 );

   int compoundItem = -1;
   for( int i = 0; i < m_CompoundTypes.size(); i++ )
   {
      if( m_CompoundTypes[i].name == name )
      {
         compoundItem = i;
         break;
      }
   }

   if( compoundItem < 0 )
      return( 0 );

   QVariant result = QVariant();
   void *ptr = (void*)&(((unsigned char *)m_pData)[( n * m_ItemSize ) + m_CompoundTypes[compoundItem].offset]);

   switch( m_CompoundTypes[compoundItem].attrType )
   {
      case RveHDF5Attribute::ATTR_INTEGER:
         switch( m_CompoundTypes[compoundItem].size )
         {
            case 1:
               result = QVariant( *( (quint8*)ptr ) );
               break;
            case 2:
               result = QVariant( *( (quint16*)ptr ) );
               break;
            case 4:
               result = QVariant( *( (quint32*)ptr ) );
               break;
            case 8:
               result = QVariant( *( (quint64*)ptr ) );
               break;
         }

      case RveHDF5Attribute::ATTR_FLOAT:
         switch( m_CompoundTypes[compoundItem].size )
         {
            case 4:
               result = QVariant( *((float*)ptr) );
               break;
            case 8:
               result = QVariant( *((double*)ptr) );
               break;
         }
   }

   return( result );
}


size_t RveHDF5Compound::itemSize() const
{
   return( m_ItemSize );
}


size_t RveHDF5Compound::numItems() const
{
   return( m_NumItems );
}


/*----------------------------------------------------------------------------*/
/*!
   Retrieve total number of bytes in the dataset
   \return total number of bytes
*/
/*----------------------------------------------------------------------------*/
size_t RveHDF5Compound::size()
{
   return( m_NumItems * m_ItemSize );
}


/*----------------------------------------------------------------------------*/
/*!
   Retrieve a pointer to the raw data
   \return pointer to the raw data
*/
/*----------------------------------------------------------------------------*/
void *RveHDF5Compound::data()
{
   return( m_pData );
}


/*----------------------------------------------------------------------------*/
/*!
   Save the dataset to an hdf5 file
   \param f handle of the hdf5 file or object
   \return an HDF5::Error object
*/
/*----------------------------------------------------------------------------*/
bool RveHDF5Compound::save( hid_t f )
{
   bool ok = true;
   herr_t status;
   hid_t filetype, memtype, strtype, space, dset;
   hsize_t dims[1] = { m_NumItems };

   // Create variable-length string datatype.
   strtype = H5Tcopy( H5T_C_S1 );
   status = H5Tset_size( strtype, H5T_VARIABLE );

   // Create the compound datatype for memory.
   memtype = H5Tcreate( H5T_COMPOUND, m_ItemSize );
   for( int i = 0; i < m_CompoundTypes.size(); i++ )
   {
      hid_t field_id;
      if( m_CompoundTypes[i].attrType == RveHDF5Attribute::ATTR_INTEGER )
      {
         field_id = H5T_NATIVE_INT;
      } else
      if( m_CompoundTypes[i].attrType == RveHDF5Attribute::ATTR_STRING )
      {
         field_id = strtype;
      }

      status = H5Tinsert( memtype,
                          m_CompoundTypes[i].name.toAscii().data(),
                          m_CompoundTypes[i].offset,
                          field_id );
   }

   // Create the compound datatype for the file.  Because the standard
   // types we are using for the file may have different sizes than
   // the corresponding native types, we must manually calculate the
   // offset of each member.
   size_t compoundSize = 0;
   for( int i = 0; i < m_CompoundTypes.size(); i++ )
   {
      hid_t field_id;
      size_t field_size;
      if( m_CompoundTypes[i].attrType == RveHDF5Attribute::ATTR_INTEGER )
      {
         field_id = H5T_STD_I32BE;
         field_size = H5Tget_size( field_id );
      } else
      if( m_CompoundTypes[i].attrType == RveHDF5Attribute::ATTR_STRING )
      {
         field_id = strtype;
         field_size = H5Tget_size( field_id );//sizeof( hvl_t );
      }

      compoundSize += field_size;
   }

   filetype = H5Tcreate( H5T_COMPOUND, compoundSize );
   size_t offset = 0;
   for( int i = 0; i < m_CompoundTypes.size(); i++ )
   {
      hid_t field_id;
      size_t field_size;
      if( m_CompoundTypes[i].attrType == RveHDF5Attribute::ATTR_INTEGER )
      {
         field_id = H5T_STD_I32BE;
         field_size = H5Tget_size( field_id );
      } else
      if( m_CompoundTypes[i].attrType == RveHDF5Attribute::ATTR_STRING )
      {
         field_id = strtype;
         field_size = sizeof( hvl_t );
      }

      status = H5Tinsert( filetype,
                          m_CompoundTypes[i].name.toAscii().data(),
                          offset,
                          field_id );
      offset += field_size;
   }


   // Create dataspace.  Setting maximum size to NULL sets the maximum
   // size to be the current size.
   space = H5Screate_simple( 1, dims, NULL );

   // Create the dataset and write the compound data to it.
   dset = H5Dcreate( f,
                     m_Name.toAscii().data(),
                     filetype,
                     space,
                     H5P_DEFAULT/*, H5P_DEFAULT, H5P_DEFAULT*/);
   status = H5Dwrite( dset, memtype, H5S_ALL, H5S_ALL, H5P_DEFAULT, m_pData );

   return( ok );
}


RveHDF5Object::OBJ_TYPE RveHDF5Compound::type()
{
   return( RveHDF5Object::TYPE_COMPOUND );
}


void RveHDF5Compound::addCompoundType( QString name, RveHDF5Attribute::ATTR_TYPE attrType, size_t offset, size_t size )
{
   CompoundType t;
   t.name = name;
   t.attrType = attrType;
   t.offset = offset;
   t.size = size;

   m_CompoundTypes.append( t );
}


QStringList RveHDF5Compound::compoundItems() const
{
   QStringList result;

   for( int i = 0; i < m_CompoundTypes.size(); i++ )
   {
      result.append( m_CompoundTypes[i].name );
   }

   return( result );
}
