#include "ZMQClient.h"

#include <QDebug>

//
//SocketMonitor::SocketMonitor(ZMQClient* client)
//    : QObject(client)
//    , zmq::monitor_t()
//    , client_(client) {
//
//}
//
//SocketMonitor::~SocketMonitor() {
// //   client_
//}
//
//
//void SocketMonitor::on_event_connected(const zmq_event_t& event_, const char* addr_) {
//    emit Connectd();
//}
//
//void SocketMonitor::on_event_disconnected(const zmq_event_t& event_, const char* addr_) {
//    emit Disconnectd();
//}
//
//void SocketMonitor::doWork(QString address) {
//    try {
//        monitor(client_->GetSocket(), address.toStdString());
//    } catch (zmq::error_t e) {
//        const char* msg = e.what();
//        qDebug() << __FUNCTION__ << msg;
//    }
//}

ZMQClient::ZMQClient(QObject* parent)
    : QObject(parent)
    , ctx_(std::make_shared<zmq::context_t>(1))
    , socket_(*ctx_, zmq::socket_type::push) {
    

}

ZMQClient::~ZMQClient() {
    zmq::message_t msg;
    auto res = socket_.send(msg, zmq::send_flags::none);
    socket_.unbind(host_);
    
        int tcp_keep_alive = 0;
    socket_.setsockopt(ZMQ_LINGER, tcp_keep_alive);
    socket_.close();
    ctx_->setctxopt(ZMQ_BLOCKY, 0);
  //  ctx_.shutdown();
    ctx_->close();
    emit StopMino();
    //thread_.quit();
    //thread_.wait();
}

bool ZMQClient::ConnectToServer(const QString& address) {
    std::string host("tcp://");
    host += address.toStdString();
    socket_.connect(host);
    host_ = host;
    int tcp_keep_alive = 1;
    socket_.setsockopt(ZMQ_TCP_KEEPALIVE, tcp_keep_alive);

    int tcp_keep_idle = 120;
    socket_.setsockopt(ZMQ_TCP_KEEPALIVE_IDLE, tcp_keep_idle);

    socket_.setsockopt(ZMQ_LINGER, 10);

   /* SocketMonitor* socketMoni = new SocketMonitor(this);
    socketMoni->moveToThread(&thread_);*/

    //connect(this, &ZMQClient::operate, socketMoni, &SocketMonitor::doWork);
    //connect(this, SIGNAL(StopMino()), socketMoni, SLOT(Stop()));
    //connect(&thread_, &QThread::finished, socketMoni, &QObject::deleteLater);

    //thread_.start();

    //emit operate(QString::fromStdString(host));
    
    return true;
}

bool ZMQClient::Send(const QString& message) {
    if (!socket_.connected()) {
        qDebug() << __FUNCTION__ << "is not connected " << message;
    }

    std::string ss = message.toStdString(); 
    zmq::message_t msg(ss.data(), ss.size());
    try {
        auto res = socket_.send(msg, zmq::send_flags::none);
        qDebug() << __FUNCTION__ << message << " res:" << res.value();
    }
    catch (zmq::error_t e) {
        const char* w = e.what();
        qDebug() << __FUNCTION__ << w << " msg" << message;
    }
    
    return true;
}