//
// 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__FrSerDataSerialIO_HH
#define FrameCPP_UNIVERSAL__IMPL__FrSerDataSerialIO_HH

#if !defined( SWIGIMPORTED )
#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"
#endif /* !defined( SWIGIMPORTED ) */

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

#if !defined( SWIGIMPORTED )
namespace FrameCPP
{
    namespace Universal
    {
        class FrSerData;
        namespace FrSerDataImpl
        {
            /// \brief Serialization I/O implementation for FrSerData data
            /// structures
            ///
            /// This class provides versioned serialization support for FrSerData
            /// objects using Boost.Serialization. It handles the evolution of
            /// the FrSerData data structure across different frame specification
            /// versions (v3 through v9).
            ///
            /// \tparam FR_SER_DATA_T The FrSerData type being serialized (typically
            /// FrSerData)
            template < typename FR_SER_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 FrSerData data to an archive
                ///
                /// This method saves the FrSerData data to a serialization
                /// archive, handling version-specific data formats and field
                /// evolution in serial data structures.
                ///
                /// \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 REAL_4 sampleRate
                /// - v4: Adds table container
                /// - v7: Changes sampleRate from REAL_4 to REAL_8
                /// - v8-9: Stable structure
                ///
                /// \note SearchContainers are converted to vectors for serialization
                /// \note Sample rate type evolution handled automatically
                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( "time", time );

                        // Handle sample rate type evolution
                        if ( version >= 7 )
                        {
                            // v7+ uses REAL_8
                            ar& make_nvp( "sampleRate", sampleRate );
                        }
                        else
                        {
                            // v3-v6 use REAL_4
                            REAL_4 sampleRate_v3 = static_cast< REAL_4 >( sampleRate );
                            ar& make_nvp( "sampleRate", sampleRate_v3 );
                        }

                        ar& make_nvp( "data", data );

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

                        // Table container (v4+)
                        if ( version >= 4 )
                        {
                            std::vector< FrTable > table_vector;
                            table_vector.reserve( table.size( ) );
                            for ( const auto& item : table )
                            {
                                if ( item )
                                {
                                    table_vector.push_back( *item );
                                }
                            }
                            ar& make_nvp( "table", table_vector );
                        }
                    }
                }

                /// \brief Deserialize FrSerData data from an archive
                ///
                /// This method loads FrSerData data from a serialization archive,
                /// handling version-specific data formats 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-v6: Load REAL_4 sampleRate, convert to REAL_8
                /// - v4+: Load table container
                /// - v7+: Load REAL_8 sampleRate directly
                ///
                /// \note SearchContainers are reconstructed from vectors
                /// \note Type conversions handle sample rate evolution
                ///
                /// \warning The caller must ensure the archive contains valid
                /// FrSerData 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( "time", time );

                        // Handle sample rate type evolution
                        if ( version >= 7 )
                        {
                            // v7+ uses REAL_8
                            ar& make_nvp( "sampleRate", sampleRate );
                        }
                        else
                        {
                            // v3-v6 use REAL_4
                            REAL_4 sampleRate_v3;
                            ar& make_nvp( "sampleRate", sampleRate_v3 );
                            sampleRate = static_cast< REAL_8 >( sampleRate_v3 );
                        }

                        ar& make_nvp( "data", data );

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

                        // Table container (v4+)
                        if ( version >= 4 )
                        {
                            std::vector< FrTable > table_vector;
                            ar& make_nvp( "table", table_vector );
                            table.clear( );
                            for ( const auto& item : table_vector )
                            {
                                auto new_item = boost::shared_ptr< FrTable >( new FrTable( item ) );
                                table.push_back( new_item );
                            }
                        }
                        else
                        {
                            table.clear( );
                        }
                    }
                    else
                    {
                        // Pre-v3: Initialize with default values
                        name.clear( );
                        time = GPSTime( );
                        sampleRate = 0.0;
                        data.clear( );
                        serial.clear( );
                        table.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 type conversions and container management.
                BOOST_SERIALIZATION_SPLIT_MEMBER( )
            };

        } // namespace FrSerDataImpl
    } // namespace Universal
} // namespace FrameCPP

/// \brief Specify the class version for Boost.Serialization
///
/// This macro tells Boost.Serialization that FrSerDataImpl::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::FrSerDataImpl::Data, 9 )

#endif /* !defined( SWIGIMPORTED ) */

#endif /* FrameCPP_UNIVERSAL__IMPL__FrSerDataSerialIO_HH */