#include <ZsutEthernet.h>
#include <ZsutEthernetUdp.h>
#include <ZsutFeatures.h>

#define MAX_BUFFER 256

byte mac[] = {
  0x01, 0xFF, 0xAA, 0x12, 0x34, 0x02
};
ZsutEthernetUDP Udp;
ZsutIPAddress address_ip=ZsutIPAddress(192,168,56,101);
unsigned int localPort = 9995;
unsigned int remotePort = 9998;

unsigned char packetBuffer[MAX_BUFFER];

unsigned char getTaskBuffer[MAX_BUFFER] = "\x09\0\0\0\4\x05prime\1\x81";
unsigned char resultBuffer[MAX_BUFFER] = "\x0F\0\0\0\1\x05prime\2\1\0\0\0\0\4\0";
int len=0;

int num = 2;

void setup() {
  ZsutPinMode(ZSUT_PIN_D4, OUTPUT);
  while (!Serial) {
  }

  ZsutEthernet.begin(mac);
  Serial.println(ZsutEthernet.localIP());
  Serial.println(localPort);
  Udp.begin(localPort);
  
  ZsutDigitalWrite(ZSUT_PIN_D4, LOW);
}

bool is_prime(int n) {
    if (n <= 1) {
        return false;
    }
    for (int i = 2; i*i <= n; ++i) {
        if (n % i == 0) {
            return false;
        }
    }
    return true;
}

void loop() {
  len = 13;
  Udp.beginPacket(address_ip, remotePort);
  int r=Udp.write(getTaskBuffer, len);
  Udp.endPacket();
  
  int packetSize=Udp.parsePacket();
  if(packetSize){
    int r=Udp.read(packetBuffer, MAX_BUFFER);
    int packet_len = packetBuffer[0] | (packetBuffer[1] << 8);
    if(packet_len == 0) {
      Serial.println("Nie znaleziono zadania");
    }
    else {
      num = packetBuffer[12] | (packetBuffer[13] << 8);
      Serial.print("Sprawdzam liczbe ");
      Serial.println(num);
      resultBuffer[18] = is_prime(num);
  
      len = 19;
      resultBuffer[13] = num & 0xFF;
      resultBuffer[14] = num >> 8 & 0xFF;
      resultBuffer[15] = 0;
      resultBuffer[16] = 0;
      Udp.beginPacket(address_ip, remotePort);
      r=Udp.write(resultBuffer, len);
      Udp.endPacket();
    }
  }

  delay(1200);
}
