#include <iostream> // for standard I/O
#include <string>   // for strings
#include <csignal>  // For signals

#include "../libs/inih/INIReader.h"

#include "Camera.h"
#include "kbhit.h"
#include "Utils.h"



using namespace std;

// Signal handling for gracefull shutdown
bool sigtermReceived = false;
void signalHandler( int signum ) {
   sigtermReceived = true; 
}

int main(int argc, char *argv[])
{
    if (argc < 2) {
        cout << "Please supply the path to the config file." << endl;
        return 1;
    }

    loguru::init(argc, argv);
    loguru::set_thread_name("Main App");

    // Run the frame grabber
    Camera cam;
    INIReader cfg(argv[1]);
    cam.setConfig(cfg);

    int reportingPeriod = cfg.GetInteger("application","reporting_period", 1000);

    // Open the camera
    cam.open();

    // Check if we found and opened a camera
    if (!cam.cameraIsOpen()) {
        LOG_S(ERROR) << "Unable to open camera." << endl;
        Sleep(100);
        return 1;
    }

    // register signal SIGINT and signal handler  
    signal(SIGTERM, signalHandler); 

    // Busy wait reporting camera status
    while (!sigtermReceived) {

        Sleep(reportingPeriod);
        
        cam.report();

        // Exit strategies
        if (sigtermReceived) {
            LOG_S(INFO) << "Received sigterm, exiting app.";
            break;
        }

        if (kbhit_no_buf()) {
            int c = getchar();
            if (c == 27) {
                LOG_S(INFO) << "Received ESC command from user on stdin";
                break;
            }
                
        }

    }

    // stop threads
    cam.close();

    return 0;
}