#include "socketClient.h"
#include <iostream>

ExtendedHook::ExtendedHook(SocketClient * lowClient) {
	this->clientCommunicator_ = lowClient;
}

action ExtendedHook::acceptMessage(message * messageToReceive)
{		
	clientCommunicator_->receiveMessage(messageToReceive);
	return ACT_CONTINUE;
}

void SocketClient::receiveMessage(message * messageToAccept)
{
	listLock_.lock();
	receivedMessages_.push(messageToAccept);
	listLock_.unlock();
}

SocketClient::SocketClient()
{
    // Inicializujeme sockety
    sockets::socketsStart();

    // Vytvoříme klienta pro komunikaci
    client_ = new client_imp();

    // Vytvoříme si odběratele 
    hook_ = new ExtendedHook(this);

	client_->setHook(*hook_);
}

bool SocketClient::isActive() {
	return client_->active();
}

bool SocketClient::connectToServer(const std::string & server, unsigned long port)
{
    // Připojíme se k serveru
	return client_->connect(server.c_str(), port);
}

void SocketClient::disconnectFromServer()
{
    client_->disconnect();
}

void SocketClient::sendAndFreeMessage(const char * messageToSend)
{
	//std::cout << "SEND MESSAGE: " << messageToSend << std::endl;

    // Pošleme zprávu
	client_->send(messageToSend);

	delete messageToSend;
}

message * SocketClient::getNextMessage()
{
    message * receivedMessage = NULL;

    listLock_.lock();

	if (!receivedMessages_.empty())
    {
        receivedMessage = receivedMessages_.front();
		//std::cout << "RECV MESSAGE: " << receivedMessage->getRequestName() << std::endl;
		receivedMessages_.pop();
    }

	listLock_.unlock();

    return receivedMessage;
}

void SocketClient::pingServer() {
    protocolWriter w;
    w.beginMessage(MT_REQUEST, REQUEST_PING);
    w.endMessage(true);

    const char * message = w.copyMessage();
	sendAndFreeMessage(message);
}