//
// LDASTools frameCPP - A library implementing the LIGO/Virgo frame
// specification
//
// Copyright (C) 2019 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__PTR_STRUCTSerialIO_HH
#define FrameCPP_UNIVERSAL__IMPL__PTR_STRUCTSerialIO_HH

#if !defined( SWIGIMPORTED )
#include <boost/serialization/nvp.hpp>
#include <boost/serialization/string.hpp>
#include <boost/serialization/split_member.hpp>
#include <boost/serialization/version.hpp>
#endif /* !defined( SWIGIMPORTED ) */

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

#if !defined( SWIGIMPORTED )
namespace FrameCPP
{
    namespace Universal
    {
        class PTR_STRUCT;
        namespace PTR_STRUCTImpl
        {
            /// \brief Serialization I/O implementation for PTR_STRUCT data
            /// structures
            ///
            /// This class provides versioned serialization support for PTR_STRUCT
            /// objects using Boost.Serialization. It handles the evolution of
            /// the PTR_STRUCT data structure across different frame specification
            /// versions (v3 through v9).
            ///
            /// \tparam FR_SH_T The PTR_STRUCT type being serialized (typically
            /// PTR_STRUCT)
            template < typename FR_SH_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 PTR_STRUCT data to an archive
                ///
                /// This method saves the PTR_STRUCT data to a serialization
                /// archive, handling version-specific data formats and type
                /// conversions. It ensures backward compatibility by converting
                /// current version data to the appropriate format for the
                /// target version.
                ///
                /// \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-4: Uses INT_2U for instance field
                /// - v5+: Uses INT_4U for instance field
                /// - All versions: Uses INT_2U for class field
                ///
                /// \note class_type remains consistent across all versions
                /// \note Type conversions ensure no data loss for instance field
                template < class Archive >
                void
                save( Archive& ar, const unsigned int version ) const
                {
                    using boost::serialization::make_nvp;

                    // class field (same for all versions)
                    ar& make_nvp( "class", data_class );

                    // Handle instance field based on target version
                    if ( version >= 5 )
                    {
                        // v5+ uses INT_4U (current version)
                        ar& make_nvp( "instance", data_instance );
                    }
                    else if ( version >= 3 )
                    {
                        // v3/v4 use INT_2U
                        v3::instance_type instance_v3 =
                            static_cast< v3::instance_type >(
                                data_instance );
                        ar& make_nvp( "instance", instance_v3 );
                    }
                }

                /// \brief Deserialize PTR_STRUCT data from an archive
                ///
                /// This method loads PTR_STRUCT data from a serialization archive,
                /// handling version-specific data formats and type conversions.
                /// It ensures forward compatibility by converting older version
                /// data to the current version format.
                ///
                /// \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: Initializes with default values
                /// - v3-4: Loads INT_2U instance field, converts to INT_4U
                /// - v5+: Direct loading of INT_4U instance field
                /// - All versions: Loads INT_2U class field
                ///
                /// \note Type conversions are performed automatically
                /// \note Default values are used for unsupported versions
                ///
                /// \warning The caller must ensure the archive contains valid
                /// PTR_STRUCT data
                template < class Archive >
                void
                load( Archive& ar, const unsigned int version )
                {
                    using boost::serialization::make_nvp;

                    // class field (same for all versions)
                    if ( version >= 3 )
                    {
                        ar& make_nvp( "class", data_class );
                    }
                    else
                    {
                        // Pre-v3, default value
                        data_class = 0;
                    }

                    // Handle instance field based on source version
                    if ( version >= 5 )
                    {
                        // v5+ uses INT_4U (current version)
                        ar& make_nvp( "instance", data_instance );
                    }
                    else if ( version >= 3 )
                    {
                        // v3/v4 use INT_2U
                        v3::instance_type instance_v3;
                        ar&               make_nvp( "instance", instance_v3 );
                        data_instance =
                            static_cast< current_version::instance_type >(
                                instance_v3 );
                    }
                    else
                    {
                        // Pre-v3, default value
                        data_instance = 0;
                    }
                }

                /// \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 version differences and type conversions.
                BOOST_SERIALIZATION_SPLIT_MEMBER( )
            };

        } // namespace PTR_STRUCTImpl
    } // namespace Universal
} // namespace FrameCPP

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

#endif /* !defined( SWIGIMPORTED ) */

#endif /* FrameCPP_UNIVERSAL__IMPL__PTR_STRUCTSerialIO_HH */
