#include "archinc.h"
#include "spibpirq.h"
#include "zl_util.h"
#include "ip.h"

#include "uip/uip.h"

#if UIP_LOGGING == 1
#include <stdio.h>
void uip_log(char *msg);
#define UIP_LOG(m) uip_log(m)
#else
#define UIP_LOG(m)
#endif /* UIP_LOGGING == 1 */

#define WAKEUP_PORT (6789)

u16_t ripAddr[2] = {0xffff, 0xffff};

static struct uip_udp_conn *wakeup_conn = NULL;

void wakeapp_init(void) {
  wakeup_conn = uip_udp_new(ripAddr, HTONS(WAKEUP_PORT));
}

static unsigned char wakeIpAddr[4] = {0, 0, 0, 0};

/*
If the uIP test function uip_newdata() is non-zero, the remote host of the 
connection has sent new data. The uip_appdata pointer point to the actual data. 
The size of the data is obtained through the uIP function uip_datalen(). 
The data is not buffered by uIP, but will be overwritten after the 
application function returns, and the application will therefor have to 
either act directly on the incoming data, or by itself copy the 
incoming data into a buffer for later processing.
*/

static void newdata(void) {
  int len = uip_datalen();
  int i;

  UIP_LOG("wakeapp: got packet\r\n");

  if (len > 0) {
    // non-zero length payload: do selective wakeup
    if (parseDottedQuadV4((char *)uip_appdata, wakeIpAddr) == 0) {
      // returns 0 if the IP address given is the same as the CPU, -1 otherwise
      if (ipIsSideARMAddr(wakeIpAddr) == 0) {
        UIP_LOG("wakeapp: wakeup addr is ours -- WAKEUP\r\n");
        // assert wakeup
        spibpirqAssert();
        }
      else {
        UIP_LOG("wakeapp: wakeup addr not ours\r\n");
        }
      }
    }
  else {
    // zero-length payload: do non selective wakeup
    UIP_LOG("wakeapp: non-selective WAKEUP\r\n");
    spibpirqAssert();
   }

  // nothing to send back
  uip_slen = 0;

  return;
}

static void acked(void) {
}

static void senddata(void) {
}

void udp_appcall(void) {
  if (uip_udp_conn->rport == HTONS(WAKEUP_PORT)) {
    if(uip_newdata()) {
      newdata();
    }
  }
}
