#include <btc/block.h>
#include <btc/net.h>
#include <btc/netspv.h>

#include <sys/resource.h>
#include <stdio.h>
#include <unistd.h>

void print_mem_usage()
{
    struct rusage r_usage;
    getrusage(RUSAGE_SELF,&r_usage);
    printf("Memory usage: %ld kilobytes\n",r_usage.ru_maxrss);
}

void test_spv_sync_completed(btc_spv_client* client) {
    print_mem_usage();
    printf("Sync completed, at height %d\n", client->headers_db->getchaintip(client->headers_db_ctx)->height);
    // btc_node_group_shutdown(client->nodegroup);
}

btc_bool test_spv_header_message_processed(struct btc_spv_client_ *client, btc_node *node, btc_blockindex *newtip) {
    UNUSED(client);
    UNUSED(node);
    printf("Get SPV Header message\n");
    if (newtip) {
        printf("New headers tip height %d\n", newtip->height);
    }
    return true;
}

void test_netspv()
{
    // unlink("headers.db");
    btc_spv_client* client = btc_spv_client_new(&btc_chainparams_main, false, false);
    client->header_message_processed = test_spv_header_message_processed;
    client->sync_completed = test_spv_sync_completed;
    client->use_checkpoints = false; // Start from genesis

    btc_spv_client_load(client, "data/full.db");

    printf("Discover peers...");
    btc_spv_client_discover_peers(client, NULL);
    printf("done\n");
    printf("Start interacting with the p2p network...\n");
    btc_spv_client_runloop(client);
    btc_spv_client_free(client);
}

int main(int ac, char** av)
{
    print_mem_usage();
    test_netspv();
    return 0;
}

