#include "lwip/opt.h"
#include "lwip/stats.h"
#include "lwip/sys.h"
#include "lwip/pbuf.h"
#include "lwip/udp.h"
#include "lwip/tcp.h"
#include "lwip/dns.h"
#include "lwip/dhcp.h"
#include "lwip/init.h"
#include "lwip/netif.h"
#include "netif/etharp.h"
#include "netif/loopif.h"
#include "device.h"

#include "mbed.h"

/* Some Lights */
DigitalOut led1(LED1);
DigitalOut led2(LED2);
int x = 0;

/* Struct with hold the Ethernet Data */
struct netif    netif_data;

/* Two static html pages ready for serving, includeing http header */
const char *page[] = {
    "HTTP/1.1 200 OK\r\n"
    "Server:mbed embedded\r\n"
    "Content-Type: text/html\r\n"
    "Content-Length: 190\r\n"
    "\r\n"
    "<html>\r\n"
    "  <header>\r\n"
    "    <title>Whats up?<title>\r\n"
    "  </header>\r\n"
    "  <body>\r\n"
    "    <h1>Hello World!!11elf</h1>\r\n"
    "    <p>Have a greate day.</p>\r\n"
    "    <a href=\"/1.html\">turn  </a>\r\n"
    "  </body>\r\n"
    "</html>\r\n"
    "\r\n"
    ,
    "HTTP/1.1 200 OK\r\n"
    "Server:mbed embedded\r\n"
    "Content-Type: text/html\r\n"
    "Content-Length: 178\r\n"
    "\r\n"
    "<html>\r\n"
    "  <header>\r\n"
    "    <title>LED Power<title>\r\n"
    "  </header>\r\n"
    "  <body>\r\n"
    "    <h1>Lets rotate!!11elf</h1>\r\n"
    "    <p>Bam!!!!!!!!!!.</p>\r\n"
    "    <a href=\"/\">back</a>\r\n"
    "  </body>\r\n"
    "</html>\r\n"
    "\r\n"
};

/* Every time called if a packet is received for a */
/* TCPConnection which registerd this Callback. */
err_t recv_callback(void *arg, struct tcp_pcb *pcb, struct pbuf *p, err_t err) {
    int i;
    char *data;

    /* Check if status is ok and data is arrived. */
    if (err == ERR_OK && p != NULL) {
        /* Inform TCP that we have taken the data. */
        tcp_recved(pcb, p->tot_len);
        data = static_cast<char *>(p->payload);

        /* If the data is a GET request we can handle it. */
        if (strncmp(data, "GET ", 4) == 0) {
            for (i = 0; i < 40; i++) {
                if (((char *)data + 4)[i] == ' ' ||
                        ((char *)data + 4)[i] == '\r' ||
                        ((char *)data + 4)[i] == '\n') {
                    ((char *)data + 4)[i] = 0;
                }
            }

            /* Check the URL */
            /* We only know two URLs /1.html and default */
            /* store the URL information in our global x variable to change twinkle behaviour. */
            x = (strncmp((char *)(data + 4), "/1.html", 7) == 0)? 1: 0;
            /* Clean up the Memory */
            pbuf_free(p);

            /* Send the right page as answere. */
            if (tcp_write(pcb, (void *)page[x], strlen(page[x]), 1) != ERR_OK) {
                //error("Could not write", 0);
            }
        } else {
            /* No data arrived */
            /* That means the client closes the connection and sent us a packet with FIN flag set to 1. */
            /* We have to cleanup and destroy out TCPConnection. */
            pbuf_free(p);
        }
    }

    /* Don't panic! Everything is fine. */
    return ERR_OK;
}

/* Accept an incomming call on the registered port */
err_t accept_callback(void *arg, struct tcp_pcb *npcb, err_t err) {
    LWIP_UNUSED_ARG(arg);
    /* Subscribe a receive callback function */
    tcp_recv(npcb, &recv_callback);

    /* Don't panic! Everything is fine. */
    return ERR_OK;
}

int main(void) {
    /* Create and initialise variables */
    struct netif   *netif = &netif_data;
    struct ip_addr  ipaddr;
    struct ip_addr  netmask;
    struct ip_addr  gateway;

    Ticker tickFast, tickSlow, tickARP, eth_tick, dns_tick, dhcp_coarse, dhcp_fine;
    char *hostname = "mbed-c3p0";
    x = 0;

    /* Start Network with DHCP */
    IP4_ADDR(&netmask, 255,255,255,255);
    IP4_ADDR(&gateway, 0,0,0,0);
    IP4_ADDR(&ipaddr, 0,0,0,0);

    /* Initialise after configuration */
    lwip_init();

    netif->hwaddr_len = ETHARP_HWADDR_LEN;
    device_address((char *)netif->hwaddr);

    netif = netif_add(netif, &ipaddr, &netmask, &gateway, NULL, device_init, ip_input);
    netif->hostname = hostname;
    netif_set_default(netif);
    dhcp_start(netif); // <-- Use DHCP

    /* Initialise all needed timers */
    tickARP.attach_us( &etharp_tmr,  ARP_TMR_INTERVAL  * 1000);
    tickFast.attach_us(&tcp_fasttmr, TCP_FAST_INTERVAL * 1000);
    tickSlow.attach_us(&tcp_slowtmr, TCP_SLOW_INTERVAL * 1000);
    dns_tick.attach_us(&dns_tmr, DNS_TMR_INTERVAL * 1000);
    dhcp_coarse.attach_us(&dhcp_coarse_tmr, DHCP_COARSE_TIMER_MSECS * 1000);
    dhcp_fine.attach_us(&dhcp_fine_tmr, DHCP_FINE_TIMER_MSECS * 1000);

    /* Bind a function to a tcp port */
    struct tcp_pcb *pcb = tcp_new();
    if (tcp_bind(pcb, IP_ADDR_ANY, 80) == ERR_OK) {
        pcb = tcp_listen(pcb);
        tcp_accept(pcb, &accept_callback);
    }

    /* Give the signal that we are ready */
    printf("entering while loop\n");
    while(1) {
        device_poll();
        if (x) {
            led1 = !led1;
            wait(0.2);
        } else {
            led2 = !led2;
            wait(0.2);
        }
    }
}

