#ifndef CAMERA_H
#define CAMERA_H

#include <QObject>
#include <Mil.h>
#include <QImage>
#include <QQueue>
#include <QDebug>
#include <QString>
#include <map>
#include <string>
#include <future>

#include <chrono>
#include <iostream>
#include <vector>
#include <fstream>
#include"onnxrunner.h"
#include <sstream>
#include <opencv2/opencv.hpp>

#include <QTcpSocket>
#include <QTcpServer>
#include "globals.h"
#include "img_utils.h"
#include "color_range.h"

extern MIL_ID MilApplication;
extern MIL_ID MilSystem;

std::vector<std::vector<uint8_t>> generateMaskFromImage(const MIL_ID& inputImage, int widthBlocks, int heightBlocks, int thresholds);
std::vector<std::vector<uint8_t>> generateMaskFromMatImage(const cv::Mat& image, int widthBlocks, int heightBlocks, int thresholds);


void PadColumns(std::vector<std::vector<uint8_t>>& data, int pad_left, int pad_right, uint8_t fill_value );
std::vector<std::vector<uint8_t>> expandArray(const std::vector<std::vector<uint8_t>>& array, int newCols) ;

void VectorToImg(const std::vector<std::vector<uint8_t>>& array, const std::string& image_path);

cv::Mat mil2mat(const MIL_ID mil_img);

void convert_to_uint8(const MIL_ID& input_img, MIL_ID& output_img);
std::vector<std::vector<uint8_t>> generateMask(
    const MIL_ID& inputImg,
    int outputWidth,
    int outputHeight,
    int sizeThreshold,
    int skipLeftCols,
    int skipRightCols
    ) ;

using namespace std;
using namespace cv;

class camera
{
public:
    camera();

};

bool iniLowMac();

bool iniCamera();

bool iniColor();

bool iniOnnx();

void Start_camera();

bool DestoryCamera();

bool DestoryLowMac();

extern int SaveImg_Flag;

MIL_INT MFTYPE ProcessingFunction0(MIL_INT HookType, MIL_ID HookId, void* HookDataPtr);
MIL_INT MFTYPE ProcessingFunction1(MIL_INT HookType, MIL_ID HookId, void* HookDataPtr);


//图像处理


std::unordered_map<std::string, int> loadConfig(const std::string& filename);


extern std::map<std::string, int> params;

void read_params_from_file(const std::string& filename, std::map<std::string, int>& params) ;

void read_color(const std::string& filename, std::vector<std::string>& colors);

pair<vector<vector<uint8_t>>, vector<vector<uint8_t>>> applyRowRangeDelay(
    const vector<vector<uint8_t>>& mask,
    const vector<vector<uint8_t>>& tail,
    int rowRange
    );

pair<vector<vector<uint8_t>>, vector<vector<uint8_t>>> generateMaskWithTail(
    const MIL_ID& inputImg,
    const vector<vector<uint8_t>>& tail,
    int outputWidth,
    int outputHeight,
    int sizeThreshold,
    int rowRange,
    int skipLeftCols,
    int skipRightCols
    );

std::vector<std::vector<uint8_t>> expandMaskHorizontally(
    const std::vector<std::vector<uint8_t>>& mask,
    int expansionRadius);


//下位机通讯
extern QTcpServer* server_to_lowermachine;
extern QTcpSocket* lower_machine;
extern bool volatile is_running;

bool get_valve_data(std::vector<std::vector<uint8_t>> mask );

#endif // CAMERA_H
