//
// 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__FrRawDataSerialIO_HH
#define FrameCPP_UNIVERSAL__IMPL__FrRawDataSerialIO_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/FrRawDataData.hh"

#if !defined( SWIGIMPORTED )
namespace FrameCPP
{
    namespace Universal
    {
        class FrRawData;
        namespace FrRawDataImpl
        {
            /// \brief Serialization I/O implementation for FrRawData data
            /// structures
            ///
            /// This class provides versioned serialization support for
            /// FrRawData objects using Boost.Serialization. It handles the
            /// stable FrRawData data structure across different frame
            /// specification versions (v3 through v9).
            ///
            /// \tparam FR_RAW_DATA_T The FrRawData type being serialized
            /// (typically FrRawData)
            template < typename FR_RAW_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 FrRawData data to an archive
                ///
                /// This method saves the FrRawData data to a serialization
                /// archive, handling the SearchContainer fields by converting
                /// them to vectors for serialization.
                ///
                /// \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+: All fields supported (name, firstSer, firstAdc,
                /// logMsg, more)
                /// - v4+: Adds table container
                /// - Pre-v3: Not supported, FrRawData structure undefined
                ///
                /// \note SearchContainers are converted to vectors for
                /// serialization \note All container types are handled
                /// uniformly
                template < class Archive >
                void
                save( Archive& ar, const unsigned int version ) const
                {
                    using boost::serialization::make_nvp;

                    if ( version >= 3 )
                    {
                        // Raw data name
                        ar& make_nvp( "name", name );

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

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

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

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

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

                /// \brief Deserialize FrRawData data from an archive
                ///
                /// This method loads FrRawData data from a serialization
                /// archive, reconstructing SearchContainers from the serialized
                /// vectors.
                ///
                /// \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:
                /// - v3+: Loads all basic containers
                /// - v4+: Loads table container
                /// - Pre-v3: Initializes with default empty values
                ///
                /// \note SearchContainers are reconstructed from vectors
                /// \note boost::shared_ptr is used for container elements
                ///
                /// \warning The caller must ensure the archive contains valid
                /// FrRawData data
                template < class Archive >
                void
                load( Archive& ar, const unsigned int version )
                {
                    using boost::serialization::make_nvp;

                    if ( version >= 3 )
                    {
                        // Raw data name
                        ar& make_nvp( "name", name );

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

                        std::vector< FrAdcData > firstAdc_vector;
                        ar& make_nvp( "firstAdc", firstAdc_vector );
                        firstAdc.clear( );
                        for ( const auto& item : firstAdc_vector )
                        {
                            auto new_item = boost::shared_ptr< FrAdcData >(
                                new FrAdcData( item ) );
                            firstAdc.push_back( new_item );
                        }

                        std::vector< FrMsg > logMsg_vector;
                        ar& make_nvp( "logMsg", logMsg_vector );
                        logMsg.clear( );
                        for ( const auto& item : logMsg_vector )
                        {
                            auto new_item =
                                boost::shared_ptr< FrMsg >( new FrMsg( item ) );
                            logMsg.push_back( new_item );
                        }

                        std::vector< FrVect > more_vector;
                        ar&                   make_nvp( "more", more_vector );
                        more.clear( );
                        for ( const auto& item : more_vector )
                        {
                            auto new_item = boost::shared_ptr< FrVect >(
                                new FrVect( item ) );
                            more.push_back( new_item );
                        }

                        // Table container (v4+)
                        if ( version >= 4 )
                        {
                            std::vector< FrTable > table_vector;
                            ar& make_nvp( "table", table_vector );
                            firstTable.clear( );
                            for ( const auto& item : table_vector )
                            {
                                auto new_item = boost::shared_ptr< FrTable >(
                                    new FrTable( item ) );
                                firstTable.push_back( new_item );
                            }
                        }
                        else
                        {
                            firstTable.clear( );
                        }
                    }
                    else
                    {
                        // Pre-v3: Initialize with default values
                        name.clear( );
                        firstSer.clear( );
                        firstAdc.clear( );
                        logMsg.clear( );
                        more.clear( );
                        firstTable.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 SearchContainer to vector conversions.
                BOOST_SERIALIZATION_SPLIT_MEMBER( )
            };

        } // namespace FrRawDataImpl
    } // namespace Universal
} // namespace FrameCPP

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

#endif /* !defined( SWIGIMPORTED ) */

#endif /* FrameCPP_UNIVERSAL__IMPL__FrRawDataSerialIO_HH */
