/**
  * @project Project
  * @brief   TODO: add a brief
  * @author  lz
  * @data    2023/4/28
 **/
#include <iostream>
#include "json/json.h"
#include "AlgWheelDetect/cloud_data.h"
#include "AlgWheelDetect/detect_wheel.h"
#include "AlgWheelDetect/alg_manager.h"

#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <termios.h>
#include <unistd.h>

// 定义函数，还原终端设置
void restore_terminal_mode()
{
    struct termios t;
    tcgetattr(STDIN_FILENO, &t);
    t.c_lflag |= ICANON | ECHO;
    tcsetattr(STDIN_FILENO, TCSANOW, &t);
}

// 定义信号处理函数，在接收到SIGINT信号时退出程序
void sigint_handler(int signum)
{
    restore_terminal_mode();
    std::cout << std::endl << "Exit the program." << std::endl;
    exit(0);
}

// 定义函数，设置终端为无缓冲输入模式
void set_terminal_mode()
{
    struct termios t;
    tcgetattr(STDIN_FILENO, &t);
    t.c_lflag &= ~(ICANON | ECHO);
    tcsetattr(STDIN_FILENO, TCSANOW, &t);
}

void checkKey() {
    char c = getchar();  // 获取单个字符

    if (c == 'Q' || c == 'q')
    {
        // 如果按下了q或Q键，则退出程序
        pid_t pid = getpid();
        kill(pid, SIGTERM);
    }
}

int main(int argc, char **argv) {
    signal(SIGTERM, sigint_handler); // 注册SIGINT信号处理函数
    set_terminal_mode();            // 进入无缓冲输入模式

    VelodyneManager velodyne;
    if (!velodyne.run_measure_form("../etc/measure_config.json")) {
        return EXIT_FAILURE;
    }

    // 死循环
    while (true) {
        checkKey();
    }

    return EXIT_SUCCESS;
}