#include "Camera.h"
#include "Core/DateTime.h"
#include "Core/IoContext.h"
#include "Core/Logger.h"
#include "Core/Singleton.h"
#include "RtspServer.h"
#include "VideoInput.h"
#include "WebRTC/Streamer.h"
#include "rw_mpp_api.h"
#include <boost/asio/signal_set.hpp>
#include <fstream>

int main(int argc, char const *argv[]) {
    using namespace Core;
    LOG(info) << "app start...";
    int status = rw_mpp__init();
    if (status != 0) {
        LOG(error) << "rw_mpp__init() failed, status: " << status;
        return -1;
    }
    try {
        auto camera = Singleton<Camera>::construct();
        auto ioContext = Singleton<IoContext>::construct(std::thread::hardware_concurrency());
        auto rtsp = std::make_shared<RtspServer>(*ioContext->ioContext());
        auto streamer = std::make_shared<Streamer>(*ioContext->ioContext());
        streamer->start("amass.fun", 443);

        auto video = std::make_shared<VideoInput>(2592, 1536);
        video->setPacketHandler([&](const uint8_t *data, uint32_t size) {
            rtsp->push(data, size);
            streamer->push(data, size);
        });
        video->start();
        // video->startFileInput("/data/sdcard/HM1.264", 1280, 720);
        video->startEncode();
        boost::asio::signal_set signals(*ioContext->ioContext(), SIGINT);
        signals.async_wait([&](boost::system::error_code const &, int signal) {
            LOG(info) << "capture " << (signal == SIGINT ? "SIGINT" : "SIGTERM") << ",stop!";
            video.reset();
            rw_mpp__finalize();
            ioContext->ioContext()->stop();
        });

        ioContext->run(true);
    } catch (const boost::exception &e) {
        LOG(error) << "error";
    } catch (const std::exception &e) {
        LOG(error) << e.what();
    }

    rw_mpp__finalize();
    LOG(info) << "app exit.";
    return 0;
}
