/*
 *
 * Copyright MBARI 2016 
 */

#ifndef __app_cfg_h
#define __app_cfg_h


#include "board.h"
#include "FreeRTOS.h"
#include "task.h"

#include "FreeRTOS_Sockets.h"

#define MAX_APPS				8
#define MAX_APP_CLIENTS	3
#define MAX_TASKS				3


typedef enum {
	CTL_APP = 0,
	SERIAL_APP,
	BAT_APP,
} app_type_t;

typedef enum {
	CACHE_TYPE_TIME = 0,
	CACHE_TYPE_NEWLINE,
} serial_cache_type_t;

typedef struct STRUCT_APP_CFG APP_CFG;
typedef struct STRUCT_TASK_CFG TASK_CFG;


struct STRUCT_APP_CFG{
	uint8_t id;
	app_type_t app_type;
	char name[16];
	Socket_t master_sock;
	Socket_t clientsocks[MAX_APP_CLIENTS];
	uint16_t tcp_port;
	char *tcp_buffer;
	int (*request_handler)(void*, int, int);
	TASK_CFG *parent_task;

	// extended app config, should be of type SERIAL_CFG,
	// CONTROL_CFG or BATTERY_CFG
	void *ext_app_cfg;
};

struct STRUCT_TASK_CFG {
	APP_CFG *apps[MAX_APPS];
	int appnum;
	bool serial;
	SocketSet_t active_fds;
};

/* extended app config for serial app */
typedef struct {
	LPC_USART_T *uart;
	uint8_t uart_num;
	IRQn_Type irq;
	uint32_t baud;
	char mode[4];
	uint64_t rx_bytes;
	uint64_t tx_bytes;
	uint32_t rx_lost;
	uint32_t tx_lost;
	RINGBUFF_T rxring;
	RINGBUFF_T txring;
	uint8_t *rxbuff;
	uint8_t *txbuff;
	serial_cache_type_t cache_mode;
} SERIAL_CFG;


/* extended app config for control app */
typedef struct {
	APP_CFG *apps[MAX_APPS];
	int appnum;
	/*
	 * we keep a list which is in sync with clientsocks and indicates which app
	 * a connected client is currently configuring.
	 */
	APP_CFG* sockapp[MAX_APP_CLIENTS];
} CONTROL_CFG;

/* extended app config for battery app */
typedef struct {
	void *foo;
} BATTERY_CFG;


#define	FLASH_CFG_LOCATION	0x7fc00
#define	FLASH_CFG_SIZE			256
#define FLASH_CFG_APP_NUM		8

#define FLASH_CFG_TYPE_MASK(value)		(value & 0x0f)
#define FLASH_CFG_SERIAL_CACHE_MODE		(1<<4)


/* per app configuration stored in flash */
typedef struct {
	//app_type_t type;
	uint8_t flags;
	uint16_t port;
	// the values below are only used for the serial apps
	uint32_t baud;
	char mode[4];
} APP_FLASH_CFG;	

/* global configuration stored in flash */
typedef struct {
	char macaddr[6];
	char ipstr[16];
	char gwstr[16];
	char nmstr[16];
	APP_FLASH_CFG app_cfgs[FLASH_CFG_APP_NUM];
	uint8_t chksum; /* sum of all bytes +1 to determine if entry is valid */
} FLASH_CFG;

#endif
