/*
 * 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 _PASSDB_H
#define _PASSDB_H

#define CREDENTIAL_LEN	(32)
#define RULENAME_LEN	(24)
#define PARAM_LEN	(24)

#define ID_INVALID 	(0)

typedef unsigned long long seq_t;
typedef unsigned long long logical_card_id_t;

//THIS STRUCTURE MUST BE A POWER OF 2 BYTES IN SIZE
typedef struct rider_record_struct
{
    seq_t seq;				//sequence number
    logical_card_id_t  id;			//rider ID
      
    char magstripe_value[CREDENTIAL_LEN];
    char rfid_value[CREDENTIAL_LEN];
    
    char rule_name[RULENAME_LEN];
    char rule_param[PARAM_LEN];    

} rider_record;


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

} rider_node;

typedef struct passdb_context_struct
{
  rider_record *riders;
  
  rider_node *freelist;
  rider_node *activelist;
  
  rider_node *logical_card_id_hash[STORED_PASS_HASH];
  rider_node *rider_mag_hash[STORED_PASS_HASH];
  rider_node *rider_rf_hash[STORED_PASS_HASH];
  
  seq_t seq;

  //THESE ARE USED IF MMAP IS DETERMINED TO BE BROKEN...
  int mmap_broken;
  int passes_fd;

} passdb_context;


#define PASS_MAP_SIZE	(NUM_STORED_PASSES * sizeof(rider_record))



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

int format_new_passdb();
int attach_to_passdb(passdb_context *ctx);
int detach_from_passdb(passdb_context *ctx);

int delete_rider(passdb_context *ctx, rider_record *rec, int sync);
int update_rider(passdb_context *ctx, rider_record *rec, int sync);

void sync_all_riders(passdb_context *ctx);

void dump_hashes(passdb_context *ctx);

int find_mag_in_hash(passdb_context *ctx, char *mag);
int find_rf_in_hash(passdb_context *ctx, char *rfid);

#endif

