#include <sys/resource.h>
#include <sys/types.h>
#include <sys/stat.h>

#include <stdlib.h>
#include <stdio.h>
#include <signal.h>
#include <unistd.h>

#include <btc/block.h>
#include <btc/net.h>
#include <btc/utils.h>
#include <btc/serialize.h>
#include <btc/tx.h>
#include <btc/utils.h>

btc_bool file_exist(const char *filename)
{
  struct stat   buffer;   
  return (stat (filename, &buffer) == 0);
}

btc_bool read_(FILE* block_fd)
{
  uint8_t  val_uint8_t;
  uint32_t val_uint32_t;
  uint64_t val_uint64_t;
  uint256  val_uint256;

  uint32_t nb_tx = 0;
  uint64_t amount = 0;
  char hash_hex_str[65];

  fread((void*) &val_uint32_t, sizeof(int32_t), 1, block_fd);
  printf("\nHeight    : %u", val_uint32_t);

  fread((void*) &val_uint256, sizeof(uint256), 1, block_fd);
  utils_bin_to_hex(val_uint256, sizeof(uint256), hash_hex_str);
  utils_reverse_hex(hash_hex_str, 64);
  printf("\nHash      : %s", hash_hex_str);

  fread((void*) &val_uint32_t, sizeof(int32_t), 1, block_fd);
  printf("\nVersion   : %u", val_uint32_t);

  fread((void*) &val_uint32_t, sizeof(uint32_t), 1, block_fd);
  printf("\nTimestamp : %u", val_uint32_t);

  fread((void*) &val_uint32_t, sizeof(uint32_t), 1, block_fd);
  printf("\nNonce     : %u", val_uint32_t);

  fread((void*) &val_uint256, sizeof(uint256), 1, block_fd);
  utils_bin_to_hex(val_uint256, sizeof(uint256), hash_hex_str);
  utils_reverse_hex(hash_hex_str, 64);
  printf("\nPrevious  : %s", hash_hex_str);

  fread((void*) &val_uint256, sizeof(uint256), 1, block_fd);
  utils_bin_to_hex(val_uint256, sizeof(uint256), hash_hex_str);
  utils_reverse_hex(hash_hex_str, 64);
  printf("\nMerkle    : %s", hash_hex_str);

  fread((void*) &nb_tx, sizeof(int32_t), 1, block_fd);
  printf("\nNb TX     : %u", nb_tx);

  for (unsigned int i = 0; i < nb_tx; i++)
  {
    if (!fread((void*)  &val_uint256,  sizeof(uint256),  1, block_fd)) break;
    if (!fread((void*)  &val_uint32_t, sizeof(uint32_t), 1, block_fd)) break;
    if (!fread((void*)  &val_uint64_t, sizeof(uint64_t), 1, block_fd)) break;

    utils_bin_to_hex((unsigned char*)val_uint256, sizeof(uint256), hash_hex_str);
    utils_reverse_hex(hash_hex_str, 64);
    printf("\n\t%u %s %u %ju", i, hash_hex_str, val_uint32_t, val_uint64_t);

    amount += val_uint64_t;
  }

  printf("\nTotal Block Outputs Amount : %ju", amount);
  printf("\n");

  return true;
}

btc_bool write_(FILE* block_fd)
{
  return true;
}

int main(int ac, char** av)
{
  // Un fichier pour lire le block
  FILE*   block_fd;

  block_fd = fopen(av[1],"rb");
  if (block_fd == NULL) return 1;
  read_(block_fd);
  fclose(block_fd);

  return 0;
}
