//
// 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__FrTOCAdcDataSerialIO_HH
#define FrameCPP_UNIVERSAL__IMPL__FrTOCAdcDataSerialIO_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/map.hpp>
#include <boost/serialization/version.hpp>

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

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

#if !defined( SWIGIMPORTED )
namespace FrameCPP
{
    namespace Universal
    {
        namespace FrTOCImpl
        {
            /// \brief Serialization I/O implementation for FrTOCAdcData structures
            ///
            /// This class provides versioned serialization support for FrTOCAdcData
            /// objects using Boost.Serialization. It handles the Table of Contents
            /// for ADC (Analog-to-Digital Converter) data across different frame
            /// specification versions (v4 through v9).
            ///
            /// \note FrTOCAdcData was introduced in v4 of the frame specification
            template < typename FR_TOC_ADC_DATA_T >
            class FrTOCAdcDataSerialIO : public virtual FrTOCAdcDataData
            {
            public:
                /// \brief Default constructor
                ///
                /// Constructs an empty SerialIO object ready for serialization
                /// operations. The object inherits data members from the
                /// FrTOCAdcDataData base class.
                FrTOCAdcDataSerialIO( )
                {
                }

            private:
                friend class boost::serialization::access;

                /// \brief Serialize FrTOCAdcData to an archive
                ///
                /// This method saves the FrTOCAdcData to a serialization archive,
                /// handling the ADC channel mapping and position information.
                ///
                /// \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+: ADC TOC supported (nadc, channel mapping, positions)
                /// - Pre-v4: ADC TOC not supported
                ///
                /// \note Channel names and position vectors are serialized
                /// \note Maintains channel index ordering for fast lookup
                template < class Archive >
                void
                save( Archive& ar, const unsigned int version ) const
                {
                    using boost::serialization::make_nvp;

                    if ( version >= 4 )
                    {
                        // Serialize the channel key container
                        ar& make_nvp( "m_keys", m_keys );

                        // Serialize the ADC info map
                        // We need to serialize both the map structure and the 
                        // position vectors within each adc_info_type
                        
                        // First, serialize the map size
                        size_t map_size = m_info.size( );
                        ar& make_nvp( "map_size", map_size );

                        // Then serialize each map entry
                        for ( const auto& entry : m_info )
                        {
                            ar& make_nvp( "channel_name", entry.first );
                            ar& make_nvp( "position_vector", entry.second.m_positionADC );
                            ar& make_nvp( "channel_index", entry.second.m_index );
                        }
                    }
                }

                /// \brief Deserialize FrTOCAdcData from an archive
                ///
                /// This method loads FrTOCAdcData from a serialization archive,
                /// reconstructing the ADC channel mapping and position information.
                ///
                /// \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
                ///
                /// Version-specific handling:
                /// - v4+: Load ADC TOC data (channel mapping, positions)
                /// - Pre-v4: Initialize with empty values (ADC TOC not supported)
                ///
                /// \note Channel names and position vectors are reconstructed
                /// \note Channel index ordering is preserved for fast lookup
                ///
                /// \warning The caller must ensure the archive contains valid
                /// FrTOCAdcData
                template < class Archive >
                void
                load( Archive& ar, const unsigned int version )
                {
                    using boost::serialization::make_nvp;

                    if ( version >= 4 )
                    {
                        // Deserialize the channel key container
                        ar& make_nvp( "m_keys", m_keys );

                        // Deserialize the ADC info map
                        m_info.clear( );

                        // First, get the map size
                        size_t map_size;
                        ar& make_nvp( "map_size", map_size );

                        // Then deserialize each map entry
                        for ( size_t i = 0; i < map_size; ++i )
                        {
                            name_type channel_name;
                            std::vector< position_type > position_vector;
                            current_version::channel_id_type channel_index;

                            ar& make_nvp( "channel_name", channel_name );
                            ar& make_nvp( "position_vector", position_vector );
                            ar& make_nvp( "channel_index", channel_index );

                            // Reconstruct the adc_info_type
                            adc_info_type adc_info( position_vector, channel_index );
                            m_info[ channel_name ] = adc_info;
                        }
                    }
                    else
                    {
                        // Pre-v4: Initialize with empty values
                        m_keys.clear( );
                        m_info.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 complex ADC channel mapping structure.
                BOOST_SERIALIZATION_SPLIT_MEMBER( )
            };

        } // namespace FrTOCImpl
    } // namespace Universal
} // namespace FrameCPP

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

#endif /* !defined( SWIGIMPORTED ) */

#endif /* FrameCPP_UNIVERSAL__IMPL__FrTOCAdcDataSerialIO_HH */