#include <myapp/cmdargs/options.h>
#include <myapp/configuration/configproviderfactory.h>
#include "daemonfacade.h"
#include "rconfacade.h"
#include <iostream>

namespace myapp {

using namespace cmdargs;
using namespace configuration;

static void
maybe_show_help(options const& opt)
{
    if (!opt.showhelp) return;
    std::cout << options::list_all() << std::endl;
    std::exit(EXIT_SUCCESS);
}

static config
read_config(options const& opt)
{
    auto factory = config_provider_factory::create_yaml_config_provider();
    return factory->from_file(opt.config);
}

} /* namespace myapp */

int
main(int argc, char* argv[])
{
    using namespace myapp;

    try {
        auto options = options::parse_arguments(argc, argv);
        maybe_show_help(options);

        if (options.config.empty())
            options.config = u8"/etc/myapp.yml";

        auto config = read_config(options);

        if (options.rcon)
            rcon_facade{options, config}.loop();
        else
            daemon_facade{options, config}.loop();
    }
	catch (configuration::error const& e)
	{
		std::cerr << "Configuration error: " << e.what() << std::endl;
		return EXIT_FAILURE;
	}
    catch (std::exception const& e)
    {
        std::cerr << e.what() << std::endl;
		return EXIT_FAILURE;
    }

    return EXIT_SUCCESS;
}
