#include "hw_impl_unix.h"
#include <sys/types.h>       
#include <sys/socket.h>
#include <stdio.h>
#include <sys/un.h>
#include <err.h>
#include <netinet/in.h>

#define DEFAULT_SOCKET "../../groundStation/virtquad.socket"
#define SOCKET_ENV "VIRT_QUAD_SOCKET"

static int backendSocket;
static int sendSocket;

int unix_uart_reset(struct UARTDriver *self) {


	char * backend_socket_path = DEFAULT_SOCKET;
	if (getenv(SOCKET_ENV)) {
	backend_socket_path = getenv(SOCKET_ENV);
	}
	/* Unlink if it exists */
	unlink(backend_socket_path);
	printf("using socket at '%s'\n", backend_socket_path);

	/* Create socket */
	backendSocket = socket(AF_UNIX, SOCK_STREAM | SOCK_NONBLOCK, 0);


	/* Create sockaddr and bind */
	struct sockaddr_un sa;
	sa.sun_family = AF_UNIX;
	strncpy(sa.sun_path, backend_socket_path, 107);
	sa.sun_path[107] = '\0';
	if (bind(backendSocket, (struct sockaddr *) &sa, sizeof(sa))) {
		err(-1, "bind");
	}

	/* Listen */
	if (listen(backendSocket, 1)) {
		err(-1, "listen");
	}

	while (1) {
		sendSocket = accept(backendSocket, NULL, NULL);
		if (sendSocket > 0)
			break;
	}

	printf(" accpet() returned with %d\n", sendSocket);
  return 0;
}

int unix_uart_write(struct UARTDriver *self, unsigned char c) {
	printf("sending %c\n", c);
	return send(sendSocket, &c, 1, 0);
}

int unix_uart_read(struct UARTDriver *self, unsigned char *c) {
	int bytes = read(sendSocket, c, 1);
	printf("read in %d byte [%x], msg=%d\n", bytes, *c, self->msg);
	return bytes;
}