#include "lwip/opt.h"
#include "lwip/arch.h"
#include "lwip/api.h"
#include "lwip/tcp.h"

#include "http_server.h"
#include "settings_api.h"
#include "common_config.h"
#include "commands_api.h"
#include "bt_6701_settings.h"

#ifdef PRINTF_STDLIB
#include <stdio.h>
#endif
#ifdef PRINTF_CUSTOM
#include "tinystdio.h"
#endif
#include <string.h>
#include <stdlib.h>

/**
  * @brief  Обработчик http запросов
  */
void TCP_ServerServe(struct netconn *conn)
{
  struct netbuf *inbuf;
  char* buf;
  u16_t buflen;
  char value[20];
  uint8_t valueLen;  
  
  netconn_recv(conn, &inbuf);
  
  if (inbuf != NULL)
  {
    if (netconn_err(conn) == ERR_OK) 
    {
      netbuf_data(inbuf, (void**)&buf, &buflen);
      
      if (strncmp((char const *)buf, "GET /setMac.cgi", 15) == 0)
      {
		memset(value, 0, 20);
        GetParamValue(buf, "mac=", value, &valueLen);  
		
		/* Проверяем флаг ожидания MAC адреса */
		if (macWaiting) {
		  SETTINGS_SetMac(value);
		  COM_SetTestState(T1OK);
		  netconn_write(conn, "HTTP/1.0 200 OK\r\nContent-Type:text/html\r\n\r\nTrue", 47, NETCONN_NOCOPY);
		  macIsInstalled = true;
		  printf("SERNO OK\r\n");
		}
		else
		  netconn_write(conn, "HTTP/1.0 200 OK\r\nContent-Type:text/html\r\n\r\nFalse", 48, NETCONN_NOCOPY);
		  
		//file = fs_open("/STM32F4x7_files/ST.gif"); 
        //netconn_write(conn, (const unsigned char*)(file->data), (size_t)file->len, NETCONN_NOCOPY);
        //fs_close(file);
      }   
    }
  }
  netconn_close(conn);
  netbuf_delete(inbuf);
}

/**
  * @brief  TCP сервер
  */
void vTaskTcpServer(void *param)
{
  struct netconn *conn, *newconn;
  err_t err;
  
  conn = netconn_new(NETCONN_TCP);
  
  if (conn!= NULL)
  {
    err = netconn_bind(conn, NULL, 80);
    
	if (err == ERR_OK) {
      netconn_listen(conn);
      while(1) {
        netconn_accept(conn, &newconn);
        TCP_ServerServe(newconn);
        netconn_delete(newconn);
      }
    }
  }
}

/**
  * @brief  Поиск значения по имени параметра
  * @retval None
  */
uint8_t GetParamValue(char *inStr, char *paramName, char *paramValue, uint8_t *paramLen)
{
  char *beginValue = 0;
  char *endValue = 0;
  int  len = 0;
  char *strPtr = 0;
  
  strPtr = strstr(inStr, paramName);
  
  if (strPtr != 0)
  {
    beginValue = strpbrk(strPtr,"=");
    endValue = strpbrk(strPtr,"&");
    if (endValue == 0)
      endValue = strpbrk(strPtr," ");
    len = endValue - beginValue - 1;
    strncpy(paramValue, beginValue + 1, len);
    *endValue = '0';
    *beginValue = '0';
	*paramLen = len;
	return 1;
  }
  else
  {	
	*paramLen = 0;
	return 0;
  }
}
