/* -*- c++ -*- */
/* 
 * Copyright 2021 Satlab A/S.
 * 
 * This 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, or (at your option)
 * any later version.
 * 
 * This software 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 software; see the file COPYING.  If not, write to
 * the Free Software Foundation, Inc., 51 Franklin Street,
 * Boston, MA 02110-1301, USA.
 */

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include <gnuradio/io_signature.h>
#include "websocket_sink_impl.h"
#include "broadcast_server.h"

namespace gr {
  namespace satlab {

    websocket_sink::sptr
    websocket_sink::make(size_t itemsize, unsigned short port)
    {
      return gnuradio::get_initial_sptr
        (new websocket_sink_impl(itemsize, port));
    }

    /*
     * The private constructor
     */
    websocket_sink_impl::websocket_sink_impl(size_t itemsize, unsigned short port)
      : gr::sync_block("websocket_sink",
              gr::io_signature::make(1, 1, itemsize),
              gr::io_signature::make(0, 0, 0))
    {
      // Start websocket server
      d_ws_server.run(port);
    }

    /*
     * Our virtual destructor.
     */
    websocket_sink_impl::~websocket_sink_impl()
    {
      // Stop websocket server
      d_ws_server.stop();
    }

    void websocket_sink_impl::set_greeting(std::string msg)
    {
      d_ws_server.set_greeting(msg);
    }

    int
    websocket_sink_impl::work(int noutput_items,
        gr_vector_const_void_star &input_items,
        gr_vector_void_star &output_items)
    {
      size_t block_size = input_signature()->sizeof_stream_item(0);
      const float *in = (const float *) input_items[0];
      size_t bins = block_size / sizeof(*in);

      std::ostringstream ss;

      // Create JSON array
      ss << std::fixed;
      ss << std::setprecision(2);
      ss << "{\"s\": [";
      for (int i = 0; i < bins - 1; i++)
        ss << in[i] << ",";
      ss << in[bins - 1];
      ss << "]}";

      // Push to websocket server
      d_ws_server.broadcast(ss.str());

      return noutput_items;
    }

  } /* namespace satlab */
} /* namespace gr */
