#include "mbed.h"
#include "TCPCallbackConnection.h"
#include "NetServer.h"
#include "iputil.h"

DigitalOut led(LED1);

/* Every time called if a packet is received for a */
/* TCPConnection which registerd this Callback. */
err_t recv_callback(TCPCallbackConnection *arg, struct pbuf *p, err_t err) {
  printf("recv_callback\n");
  if(p==NULL) {
    printf("Connection closed by server!\n");
    delete arg;
    return ERR_OK;
  }

  while(p) {
    char * ch = (char*)p->payload;
    printf("\n>>>>>>>>>>>>\n");
    for(int i=0; i < p->len; i++) {
      printf("%c", ch[i]);
    }
    printf("\n<<<<<<<<<<<<\n");
    p = p->next;
  }
  arg->recved(p->tot_len);
  pbuf_free(p);
  return ERR_OK;
}

/* Connection etablished, lets try to get a http page */
err_t connected_callback(TCPCallbackConnection *arg, err_t err) {
  printf("Connected Callback!\n");
  char msg[] = "GET / HTTP/1.1\r\nHost: 10.1.129.90\r\n\r\n";
  if(arg->write(msg, strlen(msg)) != ERR_OK) {
    error("Could not write", 0);
  }
  return ERR_OK;                                                    
}
  struct ip_addr  ipa = ipv4addr(209,85,229,99);
int main(void) {
  struct ip_addr  ipa = ipv4addr(209,85,229,99);
  
  TCPCallbackConnection *con = new TCPCallbackConnection(
    ipa, 80, NO_SENT_FNC, &recv_callback, 
    NO_POLL_FNC, &connected_callback, NO_ERR_FNC
  );
  con->connect();

  printf("entering while loop\n");
  while(1) {
      led = !led;
      NetServer::poll();
      wait(0.1);
  }
}

