#include <gtest/gtest.h>

#include "tuple.h"
#include "packet_private.h"
#include "packet_parser.h"
#include "session_private.h"
#include "default_config.h"
#include "test_packets.h"

static uint64_t session_id_generator(uint64_t now_ms __attribute__((unused)))
{
    static uint64_t count = 0;
    return (++count);
}

#if 1
TEST(TIMEOUT, TCP_TIMEOUT_HANDSHAKE)
{
    struct packet pkt;
    struct session *sess = NULL;
    struct session_manager *mgr = NULL;

    mgr = session_manager_new(&cfg, 1);
    EXPECT_TRUE(mgr != NULL);
    session_manager_set_session_id_generator(mgr, session_id_generator);

    // S2C SYNACK Packet
    printf("\n=> Packet Parse: TCP S2C SYNACK packet\n");
    memset(&pkt, 0, sizeof(pkt));
    packet_parse(&pkt, (const char *)tcp_pkt2_s2c_syn_ack, sizeof(tcp_pkt2_s2c_syn_ack));
    printf("<= Packet Parse: done\n\n");

    // lookup session
    EXPECT_TRUE(session_manager_lookup_session_by_packet(mgr, &pkt) == NULL);
    // new session
    sess = session_manager_new_session(mgr, &pkt, 1);
    EXPECT_TRUE(sess);

    // expire session
    EXPECT_TRUE(session_manager_get_expired_session(mgr, 1 + cfg.tcp_timeout_ms.handshake) == NULL);
    sess = session_manager_get_expired_session(mgr, 1 + cfg.tcp_timeout_ms.handshake + cfg.tcp_timeout_ms.data);
    EXPECT_TRUE(sess);
    EXPECT_TRUE(session_get_current_state(sess) == SESSION_STATE_CLOSED);
    EXPECT_TRUE(session_get_closing_reason(sess) == CLOSING_BY_TIMEOUT);
    session_print(sess);
    // free session
    session_manager_free_session(mgr, sess);

    session_manager_free(mgr);
}
#endif

int main(int argc, char **argv)
{
    ::testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}
