/* Sample subscriber
Copyright (C) 2020 Jonathan Hanks

This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <https://www.gnu.org/licenses/>.
*/
#include <algorithm>
#include <chrono>
#include <iostream>
#include <memory>
#include <thread>

#include <cds-pubsub/sub.hh>

void
msg_handler( pub_sub::SubMessage msg )
{
    static pub_sub::KeyType last_key = pub_sub::NEXT_PUB_MSG( );
    std::cout << "Received msg " << msg.key( );
    if ( *( (unsigned char*)msg.data( ) ) == msg.key( ) % 256 )
    {
        std::cout << " message ok" << std::endl;
    }
    else
    {
        std::cout << " message not ok "
                  << (int)( *( (unsigned char*)msg.data( ) ) ) << std::endl;
    }
    if ( last_key != pub_sub::NEXT_PUB_MSG( ) && msg.key( ) != last_key + 1 )
    {
        std::cout << "\nUnexpected/out of order message!!!\n\n" << std::endl;
    }
    last_key = msg.key( );
}

int
main( int argc, char* argv[] )
{
    pub_sub::Subscriber s;
    // s.subscribe( "udp://127.255.255.255:9000", msg_handler );

    std::string conn_str = "multi://127.0.0.1/239.192.0.1:9000";
    if ( argc == 2 )
    {
        conn_str = argv[ 1 ];
    }
    std::cout << "connecting to " << conn_str << std::endl;

    s.subscribe( conn_str, msg_handler );

    while ( true )
    {
        std::this_thread::sleep_for( std::chrono::seconds( 1 ) );
    }
    return 0;
}
