#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 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;
  uint64_t reward = 5000000000;
  uint64_t fees   = 0;
  char hash_hex_str[65];

  printf("{\n");

  fread((void*) &val_uint32_t, sizeof(int32_t), 1, block_fd);
  printf("\n\"Height\"    : \"%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("\n\"Hash\"      : \"%s\",", hash_hex_str);

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

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

  fread((void*) &val_uint32_t, sizeof(uint32_t), 1, block_fd);
  printf("\n\"Nonce\"     : \"%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("\n\"Previous\"  : \"%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("\n\"Merkle\"    : \"%s\",", hash_hex_str);

  fread((void*) &nb_tx, sizeof(int32_t), 1, block_fd);
  printf("\n\"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);
    if (i>0) printf(",");
    printf("\n{\"Hash\":\"%s\", \"Timelock\":\"%u\",\"Amount\":\"%ju\"}", hash_hex_str, val_uint32_t, val_uint64_t);

    amount += val_uint64_t;

    // Compute reward and fees
    if (i == 0) 
    {
      while(reward > 0)
      {
        if (reward < val_uint64_t) break;
        reward /= 2;
      }
      fees = val_uint64_t - reward;
    }

  }

  printf("\n],");
  printf("\n\"Amount\" : \"%ju\",", amount);
  printf("\n\"Reward\" : \"%ju\",", reward);
  printf("\n\"Fees\" : \"%ju\"", fees);
  printf("\n}\n");

  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;
}
