#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <netdb.h>
#include <sys/socket.h>

#include <logger.h>
#include <helpers.h>

int
helper_connect_tcp_server(char* host, uint16_t port)
{
    char port_str[6];
    sprintf(port_str, "%d", port);

    int s;
    int status;
    struct addrinfo *res;
    struct addrinfo hints;

    memset(&hints, 0, sizeof hints);
    hints.ai_family = AF_INET; //set IP Protocol flag (IPv4 or IPv6 - we don't care)
    hints.ai_socktype = SOCK_STREAM; //set socket flag

    if ((status = getaddrinfo(host, port_str, &hints, &res)) != 0) { //getaddrinfo() will evaluate the given address, using the hints-flags and port, and return an IP address and other server infos
        LOGGER_ERR("getaddrinfo: %s\n", gai_strerror(status));
        return -1;
    }

    //res got filled out by getaddrinfo() for us
    s = socket(res->ai_family, res->ai_socktype, res->ai_protocol); //creating Socket

    if (connect(s, res->ai_addr, res->ai_addrlen) != 0) {
        LOGGER_ERR("connect() failed\n");
        freeaddrinfo(res);
        return -1;
    }

    freeaddrinfo(res);

    return s;
}