#include "UIRequestHandler.h"
#include "DaemonDM/MessageListener.h"
#include "RequestMessageHandler.h"
#include "MessageDeserializer.h"
#include "ClientAdapter/ClientAdapterStub.h"
#include "Message.h"
#include <Logger/LoggerMacroses.h>

const char* const c_LogName = "UIRequestHandler";

namespace NS_DM_Client
{
    UIRequestHandler::UIRequestHandler(ClientAdapterStub& clientAdapterStub): m_listener(new(std::nothrow) MessageListener()), 
        m_clientAdapterStub(clientAdapterStub), m_callback(0)
    {
        if(m_listener == NULL) GDLWARN("m_listener is NULL");

        IMessageHandler* messageHandler = new(std::nothrow) RequestMessageHandler(this); // messageHandler will be freed in MessageListener
        if(messageHandler == NULL) GDLWARN("m_listener is NULL");

        m_listener->Init(messageHandler);
        m_listener->WaitMessages();
    }
    //-------------------------------------------------------------------------------------------

    UIRequestHandler::~UIRequestHandler()
    {
        m_listener->StopWaitingMessages();
        delete m_listener;
    }
    //-------------------------------------------------------------------------------------------

    void UIRequestHandler::NotifyClientStopping()
    {
        if (m_callback)
            m_callback->operator()(0, "", e_ClientStop);
    }
    //-------------------------------------------------------------------------------------------

    bool UIRequestHandler::SendRequest(const String& message, IResponseCallback* callback)
    {
        m_callback = callback;
        m_clientAdapterStub.sendConfirmationRequest(message);
        return true;
    }
    //-------------------------------------------------------------------------------------------

    void UIRequestHandler::NotifyResponse(const String& data)
    {
        String messageRequest;
        size_t confCode;
        DeserializeConfirmationResponse(data, messageRequest, confCode);

        if (m_callback)
            m_callback->operator ()(0, messageRequest, (ResponseCode)confCode);
    }
}
