#include "Client.h"

Client::Client(std::string IP, int port): m_IP(IP), m_port(port)
{
    m_csock.recsize = sizeof(m_csock.sin);
    std::cout << "-°*,-Programme Client-,*°-" << std::endl;
    std::cout << "Initialisation..." << std::endl;
    #ifdef WIN32
        m_erreur = WSAStartup(MAKEWORD(2,2), &m_WSAData);
    #else
        m_erreur = 0;
    #endif // WIN32
}

Client::~Client()
{
    std::cout << "Fermeture de la socket client" << std::endl;
    closesocket(m_csock.sock);
    std::cout << "Fermeture du client termine" << std::endl;
    #ifdef WIN32
        WSACleanup();
    #endif // WIN32
}



bool Client::rendreUtilisable()
{
    if(!m_erreur)
    {
        m_csock.sock = socket(AF_INET,SOCK_STREAM, 0);
        if(m_csock.sock != INVALID_SOCKET)
        {
            std::cout << "La socket " << m_csock.sock << " est maintenant ouverte en mode TCP/IP" << std::endl;
            m_csock.sin.sin_addr.s_addr = inet_addr(m_IP.c_str());
            m_csock.sin.sin_family = AF_INET;
            m_csock.sin.sin_port = htons(m_port);

            if(connect(m_csock.sock, (SOCKADDR*)&m_csock.sin, m_csock.recsize) != SOCKET_ERROR)
            {
                std::cout << "Connection a " << inet_ntoa(m_csock.sin.sin_addr) << " sur le port " << htons(m_csock.sin.sin_port) << " reussie" << std::endl;
            }
            else
                return false;
        }
        else
            return false;
    }
    else
        return false;
    return true;
}

void Client::envoyer(void* donnee, int tailleByte)
{
    if(tailleByte != 0)
        send(m_csock.sock, (char*)donnee, tailleByte, 0);
    else
        send(m_csock.sock, (char*)donnee, sizeof(donnee), 0);
}

void Client::recevoir(void* donnee, int tailleByte)
{
    if(tailleByte != 0)
        recv(m_csock.sock, (char*)donnee, tailleByte, 0);
    else
        recv(m_csock.sock, (char*)donnee, sizeof(donnee), 0);
}
