#include "pcap-thread.h"
#include "rssi_list.h"
#include "radiotap_iter.h"
#include <pcap.h>
#include <semaphore.h>
#include <signal.h>


extern volatile sig_atomic_t got_sigint;
extern Element * rssi_list;
extern sem_t synchro;

typedef struct {
	unsigned short fc;
	unsigned short durid;
	u_char a1[6];
	u_char a2[6];
	u_char a3[6];
	unsigned short seq;
	u_char a4[6];
}__attribute__((__packed__)) dot11_header;

void *pcap_function(void *arg)
{
  char *iface = (char *) arg;
  char errbuf[PCAP_ERRBUF_SIZE];
  pcap_t * handle = NULL;
  //struct ieee80211_radiotap_header * rtap_head;
  //struct ieee80211_header * eh;
  struct pcap_pkthdr header;
  const u_char * packet;
  //struct ieee80211_radiotap_header * packet;
  //u_char * mac;
  //u_char first_flags;
  int retCode;//offset = 0, 
  //int rssi;
  //Element * dev_info;
  struct ieee80211_radiotap_iterator iterator;
  struct ieee80211_radiotap_vendor_namespaces vns;
  
  // Open pcap handle to sniff traffic
  handle = pcap_open_live(iface, BUFSIZ, 1, 1000, errbuf);
  if (handle == NULL) {
    printf("Could not open pcap on %s\n", iface);
    pthread_exit((void *) -1);
  } 

  while (got_sigint == 0) {
    packet = pcap_next(handle, &header);
	printf("trace0\n");
    if (!packet)
	continue;
     
    //rtap_head = (struct ieee80211_radiotap_header *) packet;
    

    //initialisation de l'itérateur pour explorer les paquets
    retCode= ieee80211_radiotap_iterator_init( &iterator, (struct ieee80211_radiotap_header *) packet,25,&vns);
	printf("trace1 %d\n",retCode);
    if(retCode!=0) continue;

    int len = iterator._max_length;
    
	int rssi=0;
	printf("trace\n");
    //boucle d'exploration de la trame pour trouver la partie du packet contenant le bon header
    while(!(retCode = ieee80211_radiotap_iterator_next(&iterator)))
    {
	printf("search rssi\n");
	if(iterator.this_arg_index== IEEE80211_RADIOTAP_DBM_ANTSIGNAL) {
		printf("find\n");
		rssi=(int)iterator.this_arg[0];
	}
	
    }
	dot11_header * mac = (dot11_header*)(packet + len * sizeof(char));
	//int offset = 2 * sizeof(unsigned short);
	printf("%d bytes -- %02X:%02X:%02X:%02X:%02X:%02X -- RSSI: %d dBm\n", len, mac->a1[0], mac->a1[1], mac->a1[2], mac->a1[3], mac->a1[4], mac->a1[5], rssi);
	
	

	printf("RSSI: %d dBm\n",rssi);

	
      // We got some message issued by a terminal (FromDS=0,ToDS=1)
      printf("	Hop !\n");
          /*sem_wait(&synchro);
          if ((dev_info = find_mac(rssi_list, mac)) == NULL)
            dev_info = add_element(&rssi_list, mac);
          clear_outdated_values(&dev_info->measurements);
          //add_value(&dev_info->measurements, (int) rssi);
          //printf("post sem_t\n");
          sem_post(&synchro);*/
    
  }
  pcap_close(handle);
  pthread_exit((void *) 0);
}
