#include "UnixSocketInterface.h"

#include "HttpResponse.h"

#include "HttpMessageHandler.h"

#include <iostream>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

UnixSocketInterface::UnixSocketInterface()
    : mBufferSize(1024)
{
	mMessageHandler = std::make_unique<HttpMessageHandler>();
}

std::unique_ptr<UnixSocketInterface> UnixSocketInterface::Create()
{
    return std::make_unique<UnixSocketInterface>();
}

UnixSocketInterface::~UnixSocketInterface()
{

}

void UnixSocketInterface::InitializeSocket(const SocketPtr& socketPtr, const std::string& address)
{
    auto handle = ::socket(AF_INET, SOCK_STREAM, 0);
    socketPtr->SetHandle(handle);

    if (!address.empty())
    {
    	socketPtr->setAddress(address);
    }
}

void UnixSocketInterface::Write(const SocketPtr& socket, const std::string& message)
{
    if(socket->GetHandle() < 0)
    {
         std::cerr << "Error opening socket" << std::endl;
         return;
    }

    const auto port = static_cast<int>(socket->GetPort());
    struct sockaddr_in serv_addr;
    memset(&serv_addr, 0, sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;

    inet_aton(socket->getAddress().c_str(), &serv_addr.sin_addr);
    serv_addr.sin_port = htons(port);

    int result = connect(socket->GetHandle(), (struct sockaddr *)&serv_addr, sizeof(serv_addr));
    if(result< 0)
    {
        std::cerr << "Error connecting to socket" << std::endl;
        return;
    }

    auto n = write(socket->GetHandle(), message.c_str(), message.length());
    if (n < 0)
    {
         std::cerr << "Error on write" << std::endl;
         return;
    }

    char buffer[mBufferSize] = {0};
    int res = read(socket->GetHandle(), buffer, mBufferSize);
    if (res < 0)
    {
        std::cerr << "Error on read" << std::endl;
        return;
    }
    socket->SetMessage(buffer);
    std::cout << "Here is the message: " << buffer << std::endl;
}

void UnixSocketInterface::Listen(const SocketPtr& socket)
{
    if(socket->GetHandle() < 0)
    {
         std::cerr << "Error opening socket" << std::endl;
         return;
    }

    const auto port = static_cast<int>(socket->GetPort());
    struct sockaddr_in serv_addr;
    memset(&serv_addr, 0, sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_addr.s_addr = INADDR_ANY;
    serv_addr.sin_port = htons(port);

    int result = bind(socket->GetHandle(), (struct sockaddr *)&serv_addr, sizeof(serv_addr));
    if(result< 0)
    {
        std::cerr << "Error binding socket" << std::endl;
        return;
    }

    listen(socket->GetHandle(), 5);
}

void UnixSocketInterface::Run(const SocketPtr& socket)
{
    if(socket->GetHandle() < 0)
    {
         std::cerr << "Error opening socket" << std::endl;
         return;
    }

    struct sockaddr_in cli_addr;
    socklen_t clilen = sizeof(cli_addr);
    while(true)
    {
        const auto new_socket_handle = accept(socket->GetHandle(), (struct sockaddr *) &cli_addr, &clilen);
        if (new_socket_handle < 0)
        {
            std::cerr << "Error on accept" << std::endl;
            return;
        }

        char buffer[mBufferSize] = {0};
        int n = read(new_socket_handle, buffer, mBufferSize);
        if (n < 0)
        {
            std::cerr << "Error on read" << std::endl;
            return;
        }
        socket->SetMessage(buffer);
        std::cout << "Here is the message: " << buffer << std::endl;

        const auto response = mMessageHandler->onMessage(buffer);
        n = write(new_socket_handle, response.c_str(), response.length());
        if (n < 0)
        {
             std::cerr << "Error on write" << std::endl;
             return;
        }
        close(new_socket_handle);
    }
}
