//
// 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__FrTableSerialIO_HH
#define FrameCPP_UNIVERSAL__IMPL__FrTableSerialIO_HH

#include <boost/serialization/binary_object.hpp>
#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/FrTableData.hh"

namespace FrameCPP
{
    namespace Universal
    {
        class FrTable;
        namespace FrTableImpl
        {
            /// \brief Serialization I/O implementation for FrTable data
            /// structures
            ///
            /// This class provides versioned serialization support for FrTable
            /// objects using Boost.Serialization. It handles the evolution of
            /// the FrTable data structure across different frame specification
            /// versions (v4 through v9).
            ///
            /// \tparam FR_VECT_T The FrTable type being serialized (typically
            /// FrTable)
            template < typename FR_VECT_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 FrTable data to an archive
                ///
                /// This method saves the FrTable data to a serialization
                /// archive, handling version-specific data formats. Since
                /// FrTable structure is stable from v4 onwards, most fields
                /// are serialized consistently 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 (4-9)
                ///
                /// \throws boost::archive::archive_exception on serialization
                /// errors
                ///
                /// Version-specific handling:
                /// - v4+: All fields supported (name, comment, column vector)
                /// - Pre-v4: Not supported, FrTable was introduced in v4
                ///
                /// \note Column data is serialized as a vector of FrVect objects
                /// \note The SearchContainer is flattened to a vector for
                /// serialization
                template < class Archive >
                void
                save( Archive& ar, const unsigned int version ) const
                {
                    using boost::serialization::make_nvp;

                    if ( version >= 4 )
                    {
                        // Table name
                        ar& make_nvp( "name", name );

                        // Table comment
                        ar& make_nvp( "comment", comment );

                        // Convert SearchContainer to vector for serialization
                        std::vector< FrVect > column_vector;
                        column_vector.reserve( column.size( ) );
                        for ( const auto& col : column )
                        {
                            if ( col )
                            {
                                column_vector.push_back( *col );
                            }
                        }

                        // Serialize column data
                        ar& make_nvp( "column", column_vector );
                    }
                    // Note: FrTable was introduced in v4, so no handling for
                    // earlier versions
                }

                /// \brief Deserialize FrTable data from an archive
                ///
                /// This method loads FrTable data from a serialization archive,
                /// handling version-specific data formats. It reconstructs the
                /// SearchContainer from the serialized vector data.
                ///
                /// \tparam Archive The Boost.Serialization archive type
                ///
                /// \param[in,out] ar The archive to read data from
                /// \param[in] version The source serialization version (4-9)
                ///
                /// \throws boost::archive::archive_exception on deserialization
                /// errors \throws std::bad_alloc if memory allocation fails
                ///
                /// Version-specific handling:
                /// - v4+: Loads all fields (name, comment, column vector)
                /// - Pre-v4: Initializes with default empty values
                ///
                /// \note Column vector is reconstructed into SearchContainer
                /// \note Memory management for FrVect objects is handled
                /// automatically
                ///
                /// \warning The caller must ensure the archive contains valid
                /// FrTable data
                template < class Archive >
                void
                load( Archive& ar, const unsigned int version )
                {
                    using boost::serialization::make_nvp;

                    if ( version >= 4 )
                    {
                        // Table name
                        ar& make_nvp( "name", name );

                        // Table comment
                        ar& make_nvp( "comment", comment );

                        // Load column data as vector
                        std::vector< FrVect > column_vector;
                        ar&                   make_nvp( "column", column_vector );

                        // Clear existing columns and rebuild SearchContainer
                        column.clear( );
                        for ( const auto& col : column_vector )
                        {
                            // Create new FrVect and add to SearchContainer
                            auto new_column =
                                boost::shared_ptr< FrVect >( new FrVect( col ) );
                            column.push_back( new_column );
                        }
                    }
                    else
                    {
                        // Pre-v4: Initialize with default values
                        name.clear( );
                        comment.clear( );
                        column.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 SearchContainer to vector conversion.
                BOOST_SERIALIZATION_SPLIT_MEMBER( )
            };

        } // namespace FrTableImpl
    } // namespace Universal
} // namespace FrameCPP

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

#endif /* FrameCPP_UNIVERSAL__IMPL__FrTableSerialIO_HH */
