

#include "lwip/opt.h"
#include "lwip/sys.h"
#include "lwip/api.h"
#include "debug.h"
#include "lwip/tcp.h"
#include "commend.h"
#include "string.h"
#include "mystring.h"
#include "bytearray.h"
#include "rtthread.h"
#include "log.h"
#include "buff.h"
#include "dev_flash.h"


#define LOG_RETURN_BUFF_SIZE (1024*20)
#define LOG_TEMP_SIZE 1024


typedef struct{
  int inited;
  int run;
  data_buff data;
  rt_event_t event;
  rt_mutex_t mutex;
}self_def;


static self_def g_self;



static void log_thread(void *arg)
{
  self_def *s=&g_self;
  struct netconn *conn;
  err_t err;
  LWIP_UNUSED_ARG(arg);
  ip_addr_t dst;
  const sys_param_def *par=sys_param();
  IP4_ADDR(&dst,par->host_log_ip[0],par->host_log_ip[1],par->host_log_ip[2],par->host_log_ip[3]);
  commend_def *cmd;
  conn = netconn_new(NETCONN_UDP);
  err=netconn_bind(conn, IP_ADDR_ANY, 7778);
  uint8_t *log_temp=malloc(LOG_TEMP_SIZE);
  while (s->run) {
    if (err == ERR_OK) {
      rt_event_recv(s->event,0xffffffff,RT_EVENT_FLAG_OR|RT_EVENT_FLAG_CLEAR,RT_WAITING_FOREVER,RT_NULL);
      rt_mutex_take(s->mutex,RT_WAITING_FOREVER);
      int length=buff_get_used(&s->data);
      while(length=buff_get_used(&s->data),length>0)
      {
        if(length>LOG_TEMP_SIZE) length=LOG_TEMP_SIZE;
        struct netbuf *sbuf=netbuf_new();
        buff_read_bytes(&s->data,log_temp,length);
        netbuf_ref(sbuf,log_temp,length);
        err=netconn_sendto(conn,sbuf,&dst,par->host_log_port);
        netbuf_delete(sbuf);
      }
      rt_mutex_release(s->mutex);
    }
    else
    {
      DBG_LOG("udp:err=%d",err);
      //netconn_close(conn);
      //netconn_delete(conn);
      rt_thread_mdelay(1000);
    }
  }
}


void log_init(void)
{
  self_def *s=&g_self;
  buff_init(&s->data,LOG_RETURN_BUFF_SIZE,0,0,0);
  if(s->mutex==0){
    s->mutex=rt_mutex_create("log_mutex",RT_IPC_FLAG_FIFO);
  }
  if(s->event==0){
    s->event=rt_event_create("log_event",RT_IPC_FLAG_FIFO);
  }
  s->run=1;
  
  sys_thread_new("log_thread", log_thread, s, 2048, 29);
}




static int _open(void)
{
  self_def *s=&g_self;
  if(s->inited) return 0;
  log_init();
  s->inited=1;
  return 0;
}

static int _close(void)
{
  return 0;
}

static int _write(const uint8_t *ptr,int size)
{
  self_def *s=&g_self;
  if(s->inited)
  {
    rt_mutex_take(s->mutex,RT_WAITING_FOREVER);
    buff_save_bytes(&s->data,ptr,size);
    rt_mutex_release(s->mutex);
    rt_event_send(s->event,1);
    return size;
  }
  return 0;
}

static int _read(uint8_t *ptr,int size){
  return 0;
}

static  void *set_irqfun(void (*fun)(uint8_t d,void *context),void *context)
{
  return 0;
}


static log_typedef log_def=
{
  .init=_open,
  .write=_write,
  .read=_read,
  .set_irqfun=set_irqfun,
};


log_typedef *mylog(void)
{
  return &log_def;
}











