/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/

/**
* @file
* @copyright 2022 MPLv2
*/

#include <WHISPER/whisper.hpp>
#include <cstddef>
#include <iterator>
/**
  * @brief namespace for all whisper-com related components
  */
namespace WHISPER
{

      std::uint32_t whispercomm::getOwnID()
      {
        return ownID_;
      }


  void whispercomm::connect(std::shared_ptr<threadSafeQueue<WHISPER::Message>> receiver)
  {
    this->receiveQueue = receiver;
    this->derivedConnect();

    receiveThread = std::thread(&WHISPER::whispercomm::receive,this);

  }

  void whispercomm::disconnect()
  {
    stopReceiveThread = true;
    if(receiveThread.joinable()) receiveThread.join();
    derivedDisconnect();

  }

  void whispercomm::publish(std::string msg,std::string topic){
    this->derivedPublish(msg,topic);
  }


  void whispercomm::receive(){

    connected = true;

    derivedReceive();

    while(!stopReceiveThread)
    {
      derivedReceive();
    }
   
  }

  
  void whispercomm::subscribe(std::string topic)
  { 
    
    this->subscribedTopics.push_back(topic);
    derivedSubscribe(topic);

   
  }

  void whispercomm::unsubscribe(std::string topic)
  { 
    for (std::vector<std::string>::iterator it = subscribedTopics.begin(); it != subscribedTopics.end();it++)
    {
        if (*it  == topic)
        {
            it = subscribedTopics.erase(it);
        }
    }
    derivedUnsubscribe(topic);

  }

  void whispercomm::addMsgToReceiverQueue(WHISPER::Message msg)
  {
    if (this->receiveQueue != nullptr) 
    {
      
      this->receiveQueue->addElement(msg);

    }
  }

  void whispercomm::setGateway(bool val)
  {
    gateway = val;
  }
  bool whispercomm::isGateway(){
    return gateway;
  }
 SourceType whispercomm::getOwnDeviceType()
 {
  return ownDeviceType_;
 }


  // Add datatypes here
} // namespace WHISPER