#include <iostream>
#include <string.h>
#include <SFML/Network.hpp>
#include <SFML/System.hpp>

using namespace std;
using namespace sf;

void stressConnection(TcpSocket &s, string &ipAddr, uint16_t &port)
{
    uint8_t cpt(0);
    const char *strings[] = {"Some random data to be sent",
    "an other frame with random crap",
    "Still an other thing",
    "Last but not least me stress you even more"
    };

    char recvbuffer[4096] = "";
    size_t recvct(0);

    while(1)
    {
        s.receive(recvbuffer, 4095, recvct);
        cout << "Received : " << recvct << endl;
        cout << "Data : " << recvbuffer << endl;
        s.send(strings[cpt], strlen(strings[cpt]));
        s.disconnect();
        s.connect(ipAddr, port, sf::milliseconds(100));

        cpt = cpt >= 3 ? 0 : ++cpt;
    }
}

int main(int argc, char *argv[])
{
    string ipAddr;
    uint16_t port;
    TcpSocket ts;
    bool connected(false);

    do
    {
        cout << "Welcome to the ESP8266 TCP Stresser" << endl;
        cout << "Enter the device's IP address (IP V4)" << endl;
        cin >> ipAddr;
        cout << "Enter the server's port :" << endl;
        cin >> port;
        cout << "Connecting to " << ipAddr << " on port : " << port << endl;

        switch(ts.connect(ipAddr, port, sf::milliseconds(500)))
        {
        case Socket::Status::Error :
            cout << "Unable to connect to device" << endl;
            break;
        case Socket::Status::Done :
            cout << "Done" << endl;
            connected = true;
            break;
        case Socket::Status::NotReady :
            cout << "NotReady" << endl;
            break;
        case Socket::Status::Partial :
            cout << "Partial" << endl;
            break;
        case Socket::Status::Disconnected :
            cout << "Disconnected" << endl;
            break;
        }

        if(connected)
        {
            stressConnection(ts, ipAddr, port);
        }

    }while(true);

    return 0;
}
