//
// LDASTools frameCPP - A library implementing the LIGO/Virgo frame
// specification
//
// Copyright (C) 2025 California Institute of Technology
//
// LDASTools frameCPP is free software; you may 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 (GPLv2) of the
// License or at your discretion, any later version.
//
// LDASTools frameCPP is distributed in the hope that it will be useful, but
// without any warranty or even the implied warranty of merchantability
// or fitness for a particular purpose. See the GNU General Public
// License (GPLv2) for more details.
//
// Neither the names of the California Institute of Technology (Caltech),
// The Massachusetts Institute of Technology (M.I.T), The Laser
// Interferometer Gravitational-Wave Observatory (LIGO), nor the names
// of its contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// You should have received a copy of the licensing terms for this
// software included in the file LICENSE located in the top-level
// directory of this package. If you did not, you can view a copy at
// http://dcc.ligo.org/M1500244/LICENSE
//

#ifndef FrameCPP_UNIVERSAL__IMPL__FrAdcDataSerialIO_HH
#define FrameCPP_UNIVERSAL__IMPL__FrAdcDataSerialIO_HH

#if !defined( SWIGIMPORTED ) && defined( __cplusplus )
#include <boost/serialization/nvp.hpp>
#include <boost/serialization/string.hpp>
#include <boost/serialization/split_member.hpp>
#include <boost/serialization/vector.hpp>
#include <boost/serialization/version.hpp>
#include <boost/serialization/shared_ptr.hpp>

#include "framecpp/Common/FrameSpec.hh"
#include "framecpp/Universal/impl/HelperSerialIO.hh"
#include "framecpp/Universal/impl/GPSTime.hh"
#endif /* !defined( SWIGIMPORTED ) */

#include "framecpp/Universal/impl/FrAdcDataData.hh"

#if !defined( SWIGIMPORTED ) && defined( __cplusplus )
namespace FrameCPP
{
    namespace Universal
    {
        class FrAdcData;
        namespace FrAdcDataImpl
        {
            /// \brief Serialization I/O implementation for FrAdcData data
            /// structures
            ///
            /// This class provides versioned serialization support for
            /// FrAdcData objects using Boost.Serialization. It handles the
            /// evolution of the FrAdcData data structure across different frame
            /// specification versions (v3 through v9).
            ///
            /// \tparam FR_ADC_DATA_T The FrAdcData type being serialized
            /// (typically FrAdcData)
            template < typename FR_ADC_DATA_T >
            class SerialIO : public virtual Data
            {
            public:
                /// \brief Default constructor
                ///
                /// Constructs an empty SerialIO object ready for serialization
                /// operations. The object inherits data members from the Data
                /// base class.
                SerialIO( )
                {
                }
                
                SerialIO( const SerialIO& ) = default;
                SerialIO( SerialIO&& ) = default;
                SerialIO& operator=( const SerialIO& ) = delete;
                SerialIO& operator=( SerialIO&& ) = delete;

            private:
                friend class boost::serialization::access;

                /// \brief Serialize FrAdcData data to an archive
                ///
                /// This method saves the FrAdcData data to a serialization
                /// archive, handling version-specific data formats and field
                /// evolution. FrAdcData has changes in field names and type
                /// evolution across versions.
                ///
                /// \tparam Archive The Boost.Serialization archive type
                ///
                /// \param[in,out] ar The archive to write data to
                /// \param[in] version The target serialization version (3-9)
                ///
                /// \throws boost::archive::archive_exception on serialization
                /// errors
                ///
                /// Version-specific handling:
                /// - v3: Basic fields with crate/channel, timeOffsetS as INT_4U
                /// - v4: Renames crate->channelGroup, channel->channelNumber,
                ///       overRange->dataValid, timeOffsetS as INT_4S
                /// - v5: Changes timeOffset to REAL_8, adds phase field
                /// - v6-9: Stable structure
                ///
                /// \note Container fields (data, aux) require vector conversion
                /// \note Time offset handling changes significantly in v5
                template < class Archive >
                void
                save( Archive& ar, const unsigned int version ) const
                {
                    using boost::serialization::make_nvp;

                    if ( version >= 3 )
                    {
                        // Basic fields available in all versions
                        ar& make_nvp( "name", name ) &
                            make_nvp( "comment", comment );

                        // Handle channel field name changes
                        if ( version >= 4 )
                        {
                            ar& make_nvp( "channelGroup", channelGroup ) &
                                make_nvp( "channelNumber", channelNumber );
                        }
                        else
                        {
                            // v3 uses different field names
                            ar& make_nvp( "crate", channelGroup ) &
                                make_nvp( "channel", channelNumber );
                        }

                        // Common fields across all versions
                        ar& make_nvp( "nBits", nBits ) &
                            make_nvp( "bias", bias ) &
                            make_nvp( "slope", slope ) &
                            make_nvp( "units", units ) &
                            make_nvp( "sampleRate", sampleRate );

                        // Handle time offset evolution
                        if ( version >= 5 )
                        {
                            // v5+ uses REAL_8 timeOffset
                            ar& make_nvp( "timeOffset", timeOffset );
                        }
                        else
                        {
                            // v3/v4 use separate S/N fields
                            INT_4U timeOffsetS;
                            INT_4U timeOffsetN;
                            ConvertToSecAndNsec( timeOffset, timeOffsetS, timeOffsetN );
                            
                            if ( version >= 4 )
                            {
                                INT_4S timeOffsetS_v4 = static_cast< INT_4S >( timeOffsetS );
                                ar& make_nvp( "timeOffsetS", timeOffsetS_v4 );
                            }
                            else
                            {
                                INT_4U timeOffsetS_v3 = timeOffsetS;
                                ar& make_nvp( "timeOffsetS", timeOffsetS_v3 );
                            }
                            ar& make_nvp( "timeOffsetN", timeOffsetN );
                        }

                        ar& make_nvp( "fShift", fShift );

                        // Handle field name changes for validity
                        if ( version >= 4 )
                        {
                            ar& make_nvp( "dataValid", dataValid );
                        }
                        else
                        {
                            ar& make_nvp( "overRange", dataValid );
                        }

                        // Phase field added in v5+
                        if ( version >= 5 )
                        {
                            ar& make_nvp( "phase", phase );
                        }

                        // Convert Container to vector for serialization
                        std::vector< FrVect > data_vector;
                        data_vector.reserve( data.size( ) );
                        for ( const auto& item : data )
                        {
                            if ( item )
                            {
                                data_vector.push_back( *item );
                            }
                        }
                        ar& make_nvp( "data", data_vector );

                        std::vector< FrVect > aux_vector;
                        aux_vector.reserve( aux.size( ) );
                        for ( const auto& item : aux )
                        {
                            if ( item )
                            {
                                aux_vector.push_back( *item );
                            }
                        }
                        ar& make_nvp( "aux", aux_vector );
                    }
                }

                /// \brief Deserialize FrAdcData data from an archive
                ///
                /// This method loads FrAdcData data from a serialization
                /// archive, handling version-specific data formats and field
                /// evolution. It properly handles field name changes and type
                /// conversions.
                ///
                /// \tparam Archive The Boost.Serialization archive type
                ///
                /// \param[in,out] ar The archive to read data from
                /// \param[in] version The source serialization version (3-9)
                ///
                /// \throws boost::archive::archive_exception on deserialization
                /// errors
                ///
                /// Version-specific handling:
                /// - Pre-v3: Initialize with default values
                /// - v3: Load with original field names, convert time offset
                /// - v4: Handle field name changes, INT_4S timeOffsetS
                /// - v5+: Load REAL_8 timeOffset and phase field
                ///
                /// \note Containers are reconstructed from vectors
                /// \note Time offset conversion handles GPS time properly
                ///
                /// \warning The caller must ensure the archive contains valid
                /// FrAdcData data
                template < class Archive >
                void
                load( Archive& ar, const unsigned int version )
                {
                    using boost::serialization::make_nvp;

                    if ( version >= 3 )
                    {
                        // Basic fields available in all versions
                        ar& make_nvp( "name", name ) &
                            make_nvp( "comment", comment );

                        // Handle channel field name changes
                        if ( version >= 4 )
                        {
                            ar& make_nvp( "channelGroup", channelGroup ) &
                                make_nvp( "channelNumber", channelNumber );
                        }
                        else
                        {
                            // v3 uses different field names
                            ar& make_nvp( "crate", channelGroup ) &
                                make_nvp( "channel", channelNumber );
                        }

                        // Common fields across all versions
                        ar& make_nvp( "nBits", nBits ) &
                            make_nvp( "bias", bias ) &
                            make_nvp( "slope", slope ) &
                            make_nvp( "units", units ) &
                            make_nvp( "sampleRate", sampleRate );

                        // Handle time offset evolution
                        if ( version >= 5 )
                        {
                            // v5+ uses REAL_8 timeOffset
                            ar& make_nvp( "timeOffset", timeOffset );
                        }
                        else
                        {
                            // v3/v4 use separate S/N fields
                            INT_4U timeOffsetN;
                            if ( version >= 4 )
                            {
                                INT_4S timeOffsetS_v4;
                                ar& make_nvp( "timeOffsetS", timeOffsetS_v4 );
                                ar& make_nvp( "timeOffsetN", timeOffsetN );
                                timeOffset = ConvertToRealSeconds( 
                                    static_cast< INT_4U >( timeOffsetS_v4 ), 
                                    timeOffsetN );
                            }
                            else
                            {
                                INT_4U timeOffsetS_v3;
                                ar& make_nvp( "timeOffsetS", timeOffsetS_v3 );
                                ar& make_nvp( "timeOffsetN", timeOffsetN );
                                timeOffset = ConvertToRealSeconds( 
                                    timeOffsetS_v3, 
                                    timeOffsetN );
                            }
                        }

                        ar& make_nvp( "fShift", fShift );

                        // Handle field name changes for validity
                        if ( version >= 4 )
                        {
                            ar& make_nvp( "dataValid", dataValid );
                        }
                        else
                        {
                            ar& make_nvp( "overRange", dataValid );
                        }

                        // Phase field added in v5+
                        if ( version >= 5 )
                        {
                            ar& make_nvp( "phase", phase );
                        }
                        else
                        {
                            phase = DEFAULT_PHASE;
                        }

                        // Reconstruct containers from vectors
                        std::vector< FrVect > data_vector;
                        ar&                   make_nvp( "data", data_vector );
                        data.clear( );
                        for ( const auto& item : data_vector )
                        {
                            auto new_item = boost::shared_ptr< FrVect >(
                                new FrVect( item ) );
                            data.push_back( new_item );
                        }

                        std::vector< FrVect > aux_vector;
                        ar&                   make_nvp( "aux", aux_vector );
                        aux.clear( );
                        for ( const auto& item : aux_vector )
                        {
                            auto new_item = boost::shared_ptr< FrVect >(
                                new FrVect( item ) );
                            aux.push_back( new_item );
                        }
                    }
                    else
                    {
                        // Pre-v3: Initialize with default values
                        name.clear( );
                        comment.clear( );
                        channelGroup = 0;
                        channelNumber = 0;
                        nBits = 16; // Reasonable default
                        bias = DEFAULT_BIAS;
                        slope = DEFAULT_SLOPE;
                        units = DEFAULT_UNITS( );
                        sampleRate = 0.0;
                        timeOffset = DEFAULT_TIME_OFFSET;
                        fShift = DEFAULT_FSHIFT;
                        dataValid = DEFAULT_DATA_VALID;
                        phase = DEFAULT_PHASE;
                        data.clear( );
                        aux.clear( );
                    }
                }

                /// \brief Boost.Serialization split member macro
                ///
                /// This macro splits the serialize() method into separate
                /// save() and load() methods, allowing for different logic
                /// during serialization and deserialization. This is necessary
                /// for handling field name changes and container conversions.
                BOOST_SERIALIZATION_SPLIT_MEMBER( )
            };

        } // namespace FrAdcDataImpl
    } // namespace Universal
} // namespace FrameCPP

/// \brief Specify the class version for Boost.Serialization
///
/// This macro tells Boost.Serialization that FrAdcDataImpl::Data is at version
/// 9, which corresponds to the v9 frame specification. The serialization
/// framework uses this version number to determine how to serialize/deserialize
/// the data.
///
/// \note This version number is passed to the save() and load() methods
BOOST_CLASS_VERSION( FrameCPP::Universal::FrAdcDataImpl::Data, 9 )

/// \brief Specify the class version for the actual FrAdcData class
///
/// This ensures that when serializing FrAdcData objects directly, boost
/// knows to use version 9, which will call the proper save/load methods
/// with version >= 3 to serialize actual data instead of defaults.
BOOST_CLASS_VERSION( FrameCPP::Universal::FrAdcData, 9 )

#endif /* !defined( SWIGIMPORTED ) */

#endif /* FrameCPP_UNIVERSAL__IMPL__FrAdcDataSerialIO_HH */
