#include <SPI.h>
#include <MFRC522.h>
#include <Desfire.h>

#include "nfc.h"
#include "pins.h"
#include "helpers.h"

NFC* nfc;

void setup() 
{
    Serial.begin(115200);   // Initialize serial communications with the PC
    while (!Serial);    // Do nothing if no serial port is opened (added for Arduinos based on ATMEGA32U4)

    nfc = new NFC(PIN_RFID_SPI_SS, PIN_RFID_RST);
}

void loop()
{
    if(nfc->checkforCard())
    {
        Serial.println("Card detected");
        if(nfc->connecttoCard())
        {
            Serial.println("Card connected");

            MFRC522::StatusCode state;

            byte request_buffer[APDU_BUFFER_SIZE] = {0x90, 0x5A, 0x00, 0x00, 0x03, 0x42, 0x41, 0x46, 0x00};
            byte request_buffer_size = 9;
            byte response_buffer[APDU_BUFFER_SIZE] = {0};
            byte response_buffer_size;
            printbytes(request_buffer, request_buffer_size);

            state = nfc->Transceive(request_buffer, request_buffer_size, response_buffer, &response_buffer_size);
            if (state != MFRC522::STATUS_OK) 
            {
                Serial.println("Data Exchange failed");
                Serial.println(state);
            }
            Serial.println("Data Exchange complete");
            printbytes(response_buffer, response_buffer_size);

            state = nfc->Transceive(request_buffer, request_buffer_size, response_buffer, &response_buffer_size);
            if (state != MFRC522::STATUS_OK) 
            {
                Serial.println("Data Exchange failed");
                Serial.println(state);
            }
            Serial.println("Data Exchange complete");
            printbytes(response_buffer, response_buffer_size);

            nfc->disconnectCard();
            Serial.println("Card disconnected");
        }
    }    
}