#include <myapp/logging/loggerfactory.h>
#include <myapp/modbus/rawtcpserver.h>
#include <myapp/modbus/rawrtuclient.h>
#include <iostream>

using namespace myapp::logging;
using namespace myapp::modbus;

static void inner_main(std::string rtu_conn_str, std::string tcp_conn_str)
{
	auto logger = logger_factory::create_console_logger();
	auto mbtcp = raw_tcp_server::create(logger, tcp_conn_str);
	auto mbrtu = raw_rtu_client::create(logger, rtu_conn_str);

	mbtcp->set_data_handler([&](raw_data& adu) -> std::unique_ptr<raw_data>
	{
		try {
			return mbrtu->request(adu);
		}
		catch (std::runtime_error const&) {
			return { nullptr };
		}
	});

	mbtcp->listen(1);
	mbrtu->connect();

	for (;;)
		mbtcp->poll();
}

int main(int argc, char* argv[])
{
	if (argc != 3)
	{
		std::cerr << "Usage: modbustcp rtu:/dev/ttyS0:9600:8:N:1 tcp:0.0.0.0:502" << std::endl;
		return 1;
	}

	try
	{
		inner_main(argv[1], argv[2]);
	}
	catch (std::exception& e)
	{
		std::cerr << e.what() << std::endl;
		return 1;
	}

	return 0;
}
