#include "rfid_reader.hpp"
#include <unistd.h>
#include <iostream>
#include <chrono>
#include <ctime>
#include <chrono>

rfid_reader::rfid_reader()
	: measurement("rfid_reader")
{
	mfrc.PCD_Init();
	stop_thread = false;
	uid = 0;
	thread = std::thread(&rfid_reader::loop, this);
}

rfid_reader::~rfid_reader()
{
	 using namespace std;
	 stop_thread = true;
     thread.join();
}

uint32_t rfid_reader::last_id() const
{
	return uid.load(std::memory_order::memory_order_relaxed);
}

void rfid_reader::loop()
{
	using namespace std::chrono;
	
	stop_thread = false;
	while(!stop_thread)
	{
		std::this_thread::sleep_for(50ms);
		measurement.start();
		if(!mfrc.PICC_IsNewCardPresent())
		{
			continue;
		}
		if(!mfrc.PICC_ReadCardSerial())
		{
			continue;
		}
		

		uid.store(int((unsigned char)(mfrc.uid.uidByte[0]) << 24 |
		      (unsigned char)(mfrc.uid.uidByte[1]) << 16 |
		      (unsigned char)(mfrc.uid.uidByte[2]) << 8  |
		      (unsigned char)(mfrc.uid.uidByte[3])), std::memory_order::memory_order_relaxed);

#ifndef NDEBUG
		printf("\n");
		std::time_t result = std::time(nullptr);
		std::cout << std::asctime(std::localtime(&result));
		printf("%X\n", last_id());
#endif
		measurement.stop();
	}
}
