//
// 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__FrStatDataSerialIO_HH
#define FrameCPP_UNIVERSAL__IMPL__FrStatDataSerialIO_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/FrStatDataData.hh"

#if !defined( SWIGIMPORTED )
namespace FrameCPP
{
    namespace Universal
    {
        class FrStatData;
        namespace FrStatDataImpl
        {
            /// \brief Serialization I/O implementation for FrStatData data
            /// structures
            ///
            /// This class provides versioned serialization support for
            /// FrStatData objects using Boost.Serialization. It handles the
            /// evolution and eventual removal of the FrStatData data structure
            /// across different frame specification versions (v3 through v9).
            ///
            /// \note FrStatData was removed in v9 but is maintained for
            /// backward compatibility with v8 and earlier frames
            ///
            /// \tparam FR_STAT_DATA_T The FrStatData type being serialized
            /// (typically FrStatData)
            template < typename FR_STAT_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 FrStatData data to an archive
                ///
                /// This method saves the FrStatData data to a serialization
                /// archive, handling version-specific data formats and the
                /// structure's removal in v9.
                ///
                /// \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-8)
                ///
                /// \throws boost::archive::archive_exception on serialization
                /// errors
                ///
                /// Version-specific handling:
                /// - v3: Basic static data fields (name, comment, timeStart,
                /// etc.)
                /// - v4: Adds representation field and table container
                /// - v5-v8: Stable structure (current_version = v8)
                /// - v9: Structure removed, not supported for serialization
                ///
                /// \note SearchContainers are converted to vectors for
                /// serialization \note FrDetector is serialized as shared_ptr
                template < class Archive >
                void
                save( Archive& ar, const unsigned int version ) const
                {
                    using boost::serialization::make_nvp;

                    if ( version >= 3 && version <= 8 )
                    {
                        // Basic static data fields
                        ar& make_nvp( "name", name ) &
                            make_nvp( "comment", comment ) &
                            make_nvp( "timeStart", timeStart ) &
                            make_nvp( "timeEnd", timeEnd ) &
                            make_nvp( "version", version );

                        // Representation field (v4+)
                        if ( version >= 4 )
                        {
                            ar& make_nvp( "representation", representation );
                        }

                        // Detector (all versions)
                        ar& make_nvp( "detector", detector );

                        // Convert SearchContainers to vectors 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 );

                        // 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 );
                        }
                    }
                    // v9+: FrStatData structure was removed, no serialization
                }

                /// \brief Deserialize FrStatData data from an archive
                ///
                /// This method loads FrStatData data from a serialization
                /// archive, handling version-specific data formats and the
                /// structure's removal in v9.
                ///
                /// \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-8)
                ///
                /// \throws boost::archive::archive_exception on deserialization
                /// errors
                ///
                /// Version-specific handling:
                /// - v3: Load basic fields, no representation or table
                /// - v4+: Load representation field and table container
                /// - v9+: Initialize with default values (structure removed)
                ///
                /// \note SearchContainers are reconstructed from vectors
                /// \note Default values provided for fields not in older
                /// versions
                ///
                /// \warning The caller must ensure the archive contains valid
                /// FrStatData data for versions 3-8
                template < class Archive >
                void
                load( Archive& ar, const unsigned int version )
                {
                    using boost::serialization::make_nvp;

                    if ( version >= 3 && version <= 8 )
                    {
                        // Basic static data fields
                        ar& make_nvp( "name", name ) &
                            make_nvp( "comment", comment ) &
                            make_nvp( "timeStart", timeStart ) &
                            make_nvp( "timeEnd", timeEnd ) &
                            make_nvp( "version", version );

                        // Representation field (v4+)
                        if ( version >= 4 )
                        {
                            ar& make_nvp( "representation", representation );
                        }
                        else
                        {
                            representation.clear( );
                        }

                        // Detector (all versions)
                        ar& make_nvp( "detector", detector );

                        // Reconstruct SearchContainers 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 );
                        }

                        // 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 or v9+: Initialize with default values
                        name.clear( );
                        comment.clear( );
                        representation.clear( );
                        timeStart = 0;
                        timeEnd = 0;
                        Data::version = 0;
                        detector.reset( );
                        data.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 the structure's removal in v9 and container
                /// management.
                BOOST_SERIALIZATION_SPLIT_MEMBER( )
            };

        } // namespace FrStatDataImpl
    } // namespace Universal
} // namespace FrameCPP

/// \brief Specify the class version for Boost.Serialization
///
/// This macro tells Boost.Serialization that FrStatDataImpl::Data is at version
/// 8, which corresponds to the last supported version before removal in v9. The
/// serialization framework uses this version number to determine how to
/// serialize/deserialize the data.
///
/// \note FrStatData was removed in v9, so version 8 is the maximum supported
BOOST_CLASS_VERSION( FrameCPP::Universal::FrStatDataImpl::Data, 8 )

#endif /* !defined( SWIGIMPORTED ) */

#endif /* FrameCPP_UNIVERSAL__IMPL__FrStatDataSerialIO_HH */
