/* 
 * Copyright 2010 Stefan Lankes, Chair for Operating Systems,
 *                               RWTH Aachen University
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * This file is part of MetalSVM. 
 */

#include <metalsvm/stddef.h>
#include <metalsvm/stdio.h>
#include <metalsvm/time.h>
#include <metalsvm/tasks.h>
#include <metalsvm/semaphore.h>
#include <metalsvm/mailbox.h>
#include <metalsvm/syscall.h>
#ifdef CONFIG_ROCKCREEK
#include <asm/icc.h>
#include <asm/RCCE.h>
#include <asm/RCCE_lib.h>
#include <asm/iRCCE.h>
#include <asm/iRCCE_lib.h>

#include <asm/SCC_API.h>
#include <lwip/sockets.h>

#include "client.h"
#include "server.h"

#include "shell.h"

#endif

static sem_t 		consuming, producing;
static mailbox_int32_t	mbox;
static int 		val = 0;

static int consumer(void* arg)
{
	int 	i, m = 0;

	for(i=0; i<5; i++) {
		sem_wait(&consuming);
                kprintf("Consumer got %d\n", val);
                val = 0;
                sem_post(&producing);
        }

	for(i=0; i<5; i++) {
		mailbox_int32_fetch(&mbox, &m);
		kprintf("Got mail %d\n", m);
	}

	return 0;
}

static int producer(void* arg)
{
	int 	i;
	int 	mail[5] = {1, 2, 3, 4, 5};

	for(i=0; i<5; i++) {
		sem_wait(&producing);
		kprintf("Produce value: current val %d\n", val);
		val = 42;
		sem_post(&consuming);
	}

	for(i=0; i<5; i++) {
		//kprintf("Send mail %d\n", mail[i]);
		mailbox_int32_post(&mbox, mail[i]);
	}

	return 0;
}

static int foo(void* arg)
{
	int i;

	if (!arg)
		return 0;

	for(i=0; i<5; i++) {
		kprintf("Message from core %d: %s\n", smp_id(), (char*) arg);
		sleep(1);
	}

	return 42;
}

#ifdef CONFIG_ROCKCREEK
int mail_ping(void* arg) {
	int i;

	for(i=0; i<20; i++) {
		if (BUILTIN_EXPECT(icc_mail_ping(), 0))
			return -1;        
		udelay(500000);
	}

	return 0;
}
#endif

static int join_test(void* arg)
{
	tid_t 	id, ret;
	int 	result = -1234;

	create_kernel_task(&id, foo, "Hello from foo2");

	kprintf("Wait for child %u\n", id);
	do {
		ret = wait(&result);
	} while(ret != id);

	kprintf("Child %u finished: result = %d\n", id, result);

	return 0;
}

#if defined(CONFIG_LWIP) && defined(CONFIG_ROCKCREEK)
static int srv_cnt = 0;
void srv_on_read(ServerEventArgs* e)
{
 //       kprintf("%i:",srv_cnt);
 //       hex_dump(e->dwLen,e->pBuffer);
 //       srv_cnt++;
/*	printf("%i:",cnt);
        puts(e->pBuffer);
        puts("\n");
        cnt++;
        */
}

void srv_on_disc(ServerEventArgs*e )
{
        kprintf("connection lost!!!\n");
}

void srv_on_conn(ServerEventArgs* e)
{
    kprintf("someone finally connected\n");
}

#define SHELLDEBUGPRINTF(x,...) kprintf(x,##__VA_ARGS__);

void* server_task(void* e)
{
    int i = 0, err = 0;
    int tmp1,tmp2;
    char buff[32];

    Server	srv;

    server_init(&srv,5555,2);
    kprintf("created server\n");
    srv._OnRead = srv_on_read;
    srv._OnDisconnect = srv_on_disc;
    srv._OnConnect = srv_on_conn;
    sleep(5);
    SHELLDEBUGPRINTF("sending...\n");
    srv_sendBuffer(&srv,0,"Hello you!",sizeof("Hello you!"));
    sleep(1);

    tmp1 = get_clock_tick();
    for (i = 0; i < 1024*4*4*4; i++)
    {
            sleep(1);

            err = srv_sendBuffer(&srv,0,buff,sizeof(buff));
            if ( err < 0)
                    SHELLDEBUGPRINTF("err: %d", err);

            if (!(i%100))
                SHELLDEBUGPRINTF("\r-%d-",i);

    //	Sleep(10);
    }
    tmp2 = get_clock_tick();

    kprintf("send with %f kb/s",	((float)i*sizeof(buff))/(tmp2-tmp1));

    return NULL;

#if 0
    int sockfd, newsockfd, portno, clilen;
    char buffer[512];
    struct sockaddr_in serv_addr, cli_addr;
    int  n;
    uint64_t tmp1,tmp2;
    int err;

    /* First call to socket() function */
    sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (sockfd < 0)
    {
        SHELLDEBUGPRINTF("ERROR opening socket");
        return;
    }
    /* Initialize socket structure */
    memset((char *) &serv_addr,0, sizeof(serv_addr));
    portno = 5001;
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_addr.s_addr = INADDR_ANY;
    serv_addr.sin_port = htons(portno);

    SHELLDEBUGPRINTF("binding");
    /* Now bind the host address using bind() call.*/
    if (bind(sockfd, (struct sockaddr *) &serv_addr,
                          sizeof(serv_addr)) < 0)
    {
         SHELLDEBUGPRINTF("ERROR on binding");
         return;
    }

    /* Now start listening for the clients, here process will
    * go in sleep mode and will wait for the incoming connection
    */
    SHELLDEBUGPRINTF("listening");
    listen(sockfd,5);
    clilen = sizeof(cli_addr);

    /* Accept actual connection from the client */
    SHELLDEBUGPRINTF("accepting");
    newsockfd = accept(sockfd, (struct sockaddr *)&cli_addr,
                                &clilen);
    if (newsockfd < 0)
    {
        kprintf("ERROR on accept");
        return;
    }
    /* If connection is established then start communicating */
    memset(buffer,0,256);
    SHELLDEBUGPRINTF("recieving");
    n = recv( newsockfd,buffer,255,0 );
    if (n < 0)
    {
        SHELLDEBUGPRINTF("ERROR reading from socket");
        return;
    }
    SHELLDEBUGPRINTF("Here is the message: %s\n",buffer);

    /* Write a response to the client */
    kprintf("writing");
    n = send(newsockfd,"I got your message",18,0);
    if (n < 0)
    {
        SHELLDEBUGPRINTF("ERROR writing to socket");
        return;
    }

    tmp1 = get_clock_tick();

    for (n = 0; n < 1024*256 ; n++)
    {
        if (!(n%100))
        SHELLDEBUGPRINTF("%d-",n);
        err = send(newsockfd,buffer,sizeof(buffer),0);
        if (err < 0)
        {
            SHELLDEBUGPRINTF("error on sending: %d",err);
            break;
        }
 //       if (!(n%100))
   //         sleep(1);
    //    udelay(100);
    }

    tmp2 = get_clock_tick();

    SHELLDEBUGPRINTF("Send 1024*256 Bytes in : %d clock ticks",tmp2-tmp1);

#endif
    return 0;
}

static  int cli_cnt = 0;
void cli_on_read(ClientEventArgs* e)
{
        kprintf("\r-%d-",cli_cnt);
        cli_cnt++;
//	printf("%i:",cnt);
//	hex_dump(e->dwLen,e->pBuffer);
//	cnt++;
/*	puts(e->pBuffer);
        puts("\n");
        cnt++;
*/
}

void cli_on_disc(ClientEventArgs*e )
{
        kprintf("connection lost!!!\n");
}


void* client_task(void* e)
{

    Client cli;
    char   netbuffer[256];
    kprintf("created client");
    cli_init(&cli);
    cli._OnRead = cli_on_read;
    cli._OnDisconnect = cli_on_disc;
    sleep(1);
    while (
    cli_ConnectTo(&cli,"192.168.0.1",5555,0));
    sleep(1);
    cli_sendBuffer(&cli,"Hallo Welt",sizeof("Hallo Welt"));

    while(1)
    sleep(2);


#if 1
    while(1)
    {
            cli_sendBuffer(&cli,netbuffer,sizeof(netbuffer));
            sleep(1);
    }
#endif
    return NULL;

#if 0
        char    dir[2048];
        int	sd;
        struct sockaddr_in sin;
        struct sockaddr_in pin;
        struct hostent *hp;
        int n;

        int on = 1;

        sleep(1);

        /* fill in the socket structure with host information */
        memset(&pin, 0, sizeof(pin));
        pin.sin_family = AF_INET;
        pin.sin_addr.s_addr = inet_addr("192.168.0.1");
        pin.sin_port = htons(5001);

        /* grab an Internet domain socket */
        if ((sd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == -1) {
                kprintf("socketfail");
                return;
        }

  //      setsockopt( sd, IPPROTO_TCP, TCP_NODELAY, (char *) &on, sizeof( on));

        kprintf("connecting with socket nr : %d",sd);
        /* connect to PORT on HOST */

        if (connect(sd,(struct sockaddr *)  &pin, sizeof(pin)) == -1) {
                kprintf("connectfail");
                return;
        }
        kprintf("sending");
        /* send a message to the server PORT on machine HOST */
        if (send(sd, "HELLO THERE", strlen("HELLO THERE"), 0) == -1) {
                kprintf("sendfail");
                return;
        }
        kprintf("recieving");
        /* wait for a message to come back from the server */
        if (recv(sd, dir, 256, 0) == -1) {
                kprintf("recvfail");
                return;
        }

        /* spew-out the results and bail out of here! */
        kprintf("%s\n", dir);

        while(1)
        {
            recv(sd,dir,sizeof(dir),0);
  //          udelay(100);
        }

//	close(sd);

#endif
return NULL;
}
#endif

int test_init(void)
{
//	char* argv[] = {"/bin/tests", NULL};

//	sem_init(&producing, 1);
//	sem_init(&consuming, 0);
//	mailbox_int32_init(&mbox);

#if defined(CONFIG_LWIP) && defined(CONFIG_ROCKCREEK)

    shell_init(RCCE_ue());

    sleep(10);
    SHELLDEBUGPRINTF("hello World! I AM CORE NO. %d =) \n",RCCE_ue());

        if (!RCCE_ue())
		create_kernel_task(NULL,server_task,NULL);
	else
		create_kernel_task(NULL,client_task,NULL);
#endif

//	create_kernel_task(NULL, foo, "Hello from foo1");
//	create_kernel_task(NULL, join_test, NULL);
	//create_kernel_task(NULL, producer, NULL);
	//create_kernel_task(NULL, consumer, NULL);
	//create_kernel_task(NULL, mail_ping, NULL);
	//create_user_task(NULL, "/bin/hello", argv);
//	create_user_task(NULL, "/bin/tests", argv);
	//create_user_task(NULL, "/bin/jacobi", argv);
	//create_user_task(NULL, "/bin/jacobi", argv);

	return 0;
}