/*
 * Copyright (c) 2019 Clementine Computing LLC.
 *
 * This file is part of PopuFare.
 * 
 * PopuFare is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * PopuFare is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 * 
 * You should have received a copy of the GNU Affero General Public License
 * along with PopuFare.  If not, see <https://www.gnu.org/licenses/>.
 *
 */

#ifndef _BILLDB_H
#define _BILLDB_H


#define BILLING_CHECKSUM_SIZE	(33)	//32 bytes + NUL
#define BILLING_LINE_SIZE	(512 - BILLING_CHECKSUM_SIZE)


//THIS STRUCTURE MUST BE A POWER OF 2 BYTES IN SIZE
typedef struct billing_record_struct
{
    char checksum[BILLING_CHECKSUM_SIZE];
    char data[BILLING_LINE_SIZE];
    
} billing_record;


typedef struct billing_node_struct
{
    int idx;
    struct billing_node_struct *next;

} billing_node;

typedef struct billdb_context_struct
{
    billing_record *bills;
    time_t *last_tx;

    int num_free_records;	//count of how many nodes should be on the free list
  
    billing_node *freelist;
    billing_node *activelist;
  
    //THESE ARE USED IF MMAP IS DETERMINED TO BE BROKEN...
    int mmap_broken;
    int billing_fd;

} billdb_context;


#define BILLING_MAP_SIZE	(NUM_BILLING_ENTRIES * sizeof(billing_record))

//--------------------------

int format_new_billdb();
int attach_to_billdb(billdb_context *ctx);
int detach_from_billdb(billdb_context *ctx);

int add_billing_entry(billdb_context *ctx, char *line);
int clear_billing_entry(billdb_context *ctx, char *checksum);

int next_pending_entry(billdb_context *ctx);

#endif
