#include <iostream>
#include <fstream>
#include <opencv2/opencv.hpp>
#include <string>
#include <csignal>
#include <atomic>
#include <chrono>
#include <thread>

#include "global.h"
#include "camera.h"
#include "control.h"

std::atomic<bool> running(true);
void signalHandler(int signal)
{
    running.store(false);
}

int main(void)
{
    std::signal(SIGINT, signalHandler);

    double dest_fps = readDoubleFromFile(destfps_file);
    if (dest_fps <= 0) dest_fps = 30.0;

    cfg_load_all();

    if (CameraInit(0, dest_fps, 320, 240) < 0) {
        std::cerr << "CameraInit failed" << std::endl;
        return -1;
    }
    ControlInit();
    std::cout << "All services started" << std::endl;

    int tick = 0;
    while (running.load())
    {
        CameraHandler();

        if (++tick % 7 == 0) {
            g_cfg.debug = readFlag(debug_file);
        }

        if (g_cfg.debug) {
            cfg_load_all();
        }

        target_speed = g_cfg.speed;
    }

    std::cout << "Stopping..." << std::endl;
    std::this_thread::sleep_for(std::chrono::milliseconds(500));
    ControlExit();
    cameraDeInit();
    std::cout << "Stopped." << std::endl;
    return 0;
}
