/*************************************************  
  File name     : mw_tcpserver.h
  Module        : 
  Author        : amir 
  Version       : 0.1   
  Created on    : 2024-10-10  
  Description   :
      Data structure and function definitions required by the socket interface

  Modify History:   
  1. Date:        Author:         Modification:
*************************************************/

#include "hthread.h"
#include "mw_tcpserver.h"
#include "hlog.h"
#include "hbase.h"
#include "hsocket.h"
#include "hloop.h"
#include "hevent.h"

static void on_close(hio_t* io) {
    hlogd("on_close fd=%d error=%d\n", hio_fd(io), hio_error(io));
}

static void on_recv(hio_t* io, void* buf, int readbytes) {
    hlogd("on_recv fd=%d readbytes=%d\n", hio_fd(io), readbytes);
    char localaddrstr[SOCKADDR_STRLEN] = {0};
    char peeraddrstr[SOCKADDR_STRLEN] = {0};
    hlogd("[%s] <=> [%s]\n",
            SOCKADDR_STR(hio_localaddr(io), localaddrstr),
            SOCKADDR_STR(hio_peeraddr(io), peeraddrstr));
    hlogd("< %.*s", readbytes, (char*)buf);
    // echo
    hlogd("> %.*s", readbytes, (char*)buf);
    hio_write(io, buf, readbytes);
}

static void on_accept(hio_t* io) {
    hlogd("on_accept connfd=%d\n", hio_fd(io));
    char localaddrstr[SOCKADDR_STRLEN] = {0};
    char peeraddrstr[SOCKADDR_STRLEN] = {0};
    hlogd("accept connfd=%d [%s] <= [%s]\n", hio_fd(io),
            SOCKADDR_STR(hio_localaddr(io), localaddrstr),
            SOCKADDR_STR(hio_peeraddr(io), peeraddrstr));

    hio_setcb_close(io, on_close);
    hio_setcb_read(io, on_recv);

    hio_read_start(io);

}

void tcpserver_test(){
    const char* host = "0.0.0.0";
    int port = 8888;
    
	hloop_t* loop = hloop_new(0);
    hio_t* listenio = hloop_create_tcp_server(loop, host, port, on_accept);
    hlogd("listenfd=%d\n", hio_fd(listenio));
    hloop_run(loop);
    hloop_free(&loop);
}

