#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 = 9996;
unsigned int remotePort = 9998;

unsigned char packetBuffer[MAX_BUFFER];

unsigned char requestBuffer[MAX_BUFFER] = "\x0D\0\0\0\1\x05prime\1\1\0\0\0\0";
unsigned char getResultBuffer[MAX_BUFFER] = "\x0E\0\0\0\4\x05prime\2\1\0\0\0\0\x84";
int len=0;

int num = 2;
int num2 = 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);
}

void loop() {
  len = 17;
  requestBuffer[13] = num & 0xFF;
  requestBuffer[14] = num >> 8 & 0xFF;
  requestBuffer[15] = 0;
  requestBuffer[16] = 0;
  Serial.print("Wysylam pytanie o pierwszosc liczby ");
  Serial.println(num);
  Udp.beginPacket(address_ip, remotePort);
  int r=Udp.write(requestBuffer, len);
  Udp.endPacket();

  delay(900);
  
  len = 18;
  getResultBuffer[13] = num2 & 0xFF;
  getResultBuffer[14] = num2 >> 8 & 0xFF;
  getResultBuffer[15] = 0;
  getResultBuffer[16] = 0;
  Udp.beginPacket(address_ip, remotePort);
  r=Udp.write(getResultBuffer, len);
  Udp.endPacket();

  delay(100);
  
  int packetSize=Udp.parsePacket();
  while(packetSize){
    int r=Udp.read(packetBuffer, MAX_BUFFER);
    int packet_len = packetBuffer[0] | (packetBuffer[1] << 8);
    if(packet_len == 0) {
      Serial.print("Nie znaleziono wyniku dla liczby ");
      Serial.println(num2);
    }
    else {
      num2 = packetBuffer[12] | (packetBuffer[13] << 8);
      if(packetBuffer[17]) {
        Serial.print("Liczba ");
        Serial.print(num2);
        Serial.println(" jest liczbą pierwszą");
      }
      else {
        Serial.print("Liczba ");
        Serial.print(num2);
        Serial.println(" nie jest liczbą pierwszą");
      }
      ++num2;
    }
    packetSize=Udp.parsePacket();
  }
  ++num;
  delay(100);
}
