/*
 * meshSenderClient.cpp
 *
 *  Created on: Jul 13, 2017
 *      Author: vadims
 */

#include <websocketpp/config/asio_no_tls_client.hpp>
#include <websocketpp/client.hpp>

#include "nlohmann/json.hpp"
#include <fstream>
#include <iostream>
#include "messagedata.hpp"


typedef websocketpp::client<websocketpp::config::asio_client> client;

using websocketpp::lib::placeholders::_1;
using websocketpp::lib::placeholders::_2;
using websocketpp::lib::bind;

// pull out the type of messages sent by our config
typedef websocketpp::config::asio_client::message_type::ptr message_ptr;

// This message handler will be invoked once for each incoming message. It
// prints the message and then sends a copy of the message back to the server.

void on_message(client* c)
{
    c->stop();
}


void on_open(client* c, websocketpp::connection_hdl hdl, std::string message) 
{
    c->send(hdl, message, websocketpp::frame::opcode::text);
    c->stop();
}


int messageSender(int portNr, std::string message)
{
    std::ofstream os;
    // Create a client endpoint
    client c;
    os.open("logfile.log");
    c.get_alog().set_ostream(&os);
    c.get_elog().set_ostream(&os);

    std::string uri = "ws://[::1]:" + std::to_string(portNr) + "/?id=salome_plugin";

    try {
        // Set logging to be pretty verbose (everything except message payloads)

        // Initialize ASIO
        c.init_asio();

        // Register our message handler
        //c.set_message_handler(bind(&on_message,&c,::_1,::_2));
        c.set_message_handler(bind(&on_message, &c));
        c.set_open_handler(bind(&on_open, &c, ::_1, message));


        websocketpp::lib::error_code ec;
        client::connection_ptr con = c.get_connection(uri, ec);
        if (ec) {
            std::cout << "could not create connection because: " << ec.message() << std::endl;
            return 0;
        }

        // Note that connect here only requests a connection. No network messages are
        // exchanged until the event loop starts running in the next line.
        c.connect(con);

        // Start the ASIO io_service run loop
        // this will cause a single connection to be made to the server. c.run()
        // will exit when this connection is closed.
        c.run();
    }
    catch (websocketpp::exception const& e) {
        std::cout << e.what() << std::endl;
    }
    catch (std::exception const& e) {
        std::cout << "messageSender " << e.what() << std::endl;
    }

    os.close();
}


extern "C" __declspec(dllexport) int sendMessage(int portNr, char* message)
{
    return messageSender(portNr, message);
}