#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <chrono>
#include <iostream>
#include <csignal>
#include <sstream>
#include <Processing.NDI.Lib.h>
#include <opencv2/core/core.hpp>
#include <opencv2/opencv.hpp>
#include <array>

using namespace std::chrono;

#ifdef _WIN32
#ifdef _WIN64
#pragma comment(lib, "Processing.NDI.Lib.x64.lib")
#else // _WIN64
#pragma comment(lib, "Processing.NDI.Lib.x86.lib")
#endif // _WIN64
#endif // _WIN32

static bool is_terminated = false;

void signalHandler(int signum) {
    // Ctrl+C  -> SIGINT
    // SystemD -> SIGTERM
    std::cout << "Interrupt signal (" << signum << ") received.";
    is_terminated = true;
};

int main(int argc, char* argv[]) {
    signal(SIGINT, signalHandler);
    signal(SIGTERM, signalHandler);

    // Not required, but "correct" (see the SDK documentation.
    if (!NDIlib_initialize()) {
        return 0;
    }

    // We create the NDI sender
    NDIlib_send_instance_t pNDI_send = NDIlib_send_create();
    if (!pNDI_send) return 0;

    int64_t total_frames_counter = 0;

    // Let's open the video with OpenCV and read it
    std::string path_to_file = "C:\\Users\\ivan\\Source\\Repos\\cv_networking_pipeline\\gstreamer_receive_video\\videos\\camera1-2020-10-14---19-38-42---093390448_scaled.mp4";
    //std::string path_to_file;
    //std::cout << "Please, enter the path to the video_file" << std::endl;
    //std::cin >> path_to_file;

    std::string confirmation;

    while (true) {
        std::cout << "Please, write key y or yes to continue" << std::endl;
        std::cin >> confirmation;
        if ( (confirmation == "y") || (confirmation == "yes") ) {
            break;
        }
        confirmation = "";
    }

    cv::VideoCapture video_file(path_to_file);

    std::cout << "Video File opened" << std::endl;
    cv::Mat frame;

    int cnt = 0;

    while (!is_terminated) {
        // Get the current time
        const auto start_send = high_resolution_clock::now();

        // Send 200 frames
        for (int idx = 200; idx; idx--) {
            // Fill in the buffer. It is likely that you would do something much smarter than this.
            video_file.read(frame);
            //std::cout << "Successfully read video_file" << std::endl;
            //std::cout << "Frame channels is: " << frame.channels() << " " << frame.rows << " " << frame.cols << std::endl;
            //std::cout << frame.total() * frame.channels() << std::endl;
            // from https://stackoverflow.com/questions/26681713/convert-mat-to-array-vector-in-opencv
            // TODO: Seems that the conversion was unseccesful. Understand what really happens when you set the frame.ptr<uint8_t>(0) and what happens when 
            // TODO: you make (uint8_t*)malloc(xres * yres * 4)
            uchar* p_data = new uchar[frame.total() * 4];
            cv::Mat continiousRGBA(frame.size(), CV_8UC4, p_data);
            cv::cvtColor(frame, continiousRGBA, CV_BGR2RGBA, 4);
            //uchar* p_data = (uchar*)frame.clone().data;
            //uchar* p_data = (uchar*)frame.ptr(0);
            //std::cout << "Successfully converted frame." << std::endl;
            
            //std::cout << &p_data[50] << std::endl;
            //for (int i = 0; i < frame.total() * frame.channels(); i++) {
            //    std::cout << (int)*(p_data + i) << std::endl;
            //}
            // We are going to create a 1920x1080 interlaced frame at 29.97Hz.
            int xres = 480;
            int yres = 270;
            std::string metadata_string = "<metadata_string " + std::to_string(total_frames_counter) + std::to_string(cnt) + ">";

            // (uint8_t*)malloc(xres * yres * 4) is the frame itself. 
            NDIlib_video_frame_v2_t ndi_video_frame(
                    xres, yres, NDIlib_FourCC_type_RGBA,
                    30000, 1001, 2,
                    NDIlib_frame_format_type_progressive,
                    0,
                    p_data,
                    0,
                    metadata_string.c_str()
            );
            //std::cout << "Successfully created ndi_video_frame" << std::endl;
            // 
            // std::cout << "hi there" << std::endl;
            // std::cout << "xres = " << ndi_video_frame.xres << std::endl;
            // std::cout << "yres = " << ndi_video_frame.yres << std::endl;
            // std::cout << "frame_rate_N = " << ndi_video_frame.frame_rate_N << std::endl;
            // std::cout << "frame_rate_D = " << ndi_video_frame.frame_rate_D << std::endl;
            // std::cout << "picture_aspect_ratio = " << ndi_video_frame.picture_aspect_ratio << std::endl;
            // std::cout << "frame_format_type = " << ndi_video_frame.frame_format_type << std::endl;
            // std::cout << "timecode = " << ndi_video_frame.timecode << std::endl;
            // std::cout << "line_stride_in_bytes = " << ndi_video_frame.line_stride_in_bytes << std::endl;
            // std::cout << "p_metadata = " << ndi_video_frame.p_metadata << std::endl;
            // std::cout << "timestamp = " << ndi_video_frame.timestamp << std::endl;

            //memset((void*)ndi_video_frame.p_data, 0x33, ndi_video_frame.xres * ndi_video_frame.yres * 4);
            ndi_video_frame.timestamp = total_frames_counter;
            ndi_video_frame.timecode = total_frames_counter;
            std::cout << "timestamp and timecode success." << std::endl;
            // memset((void*)ndi_video_frame.p_data, (idx & 1) ? 255 : 0, ndi_video_frame.xres*ndi_video_frame.yres * 4);

            // We now submit the frame. Note that this call will be clocked so that we end up submitting at exactly 29.97fps.
            NDIlib_send_send_video_v2(pNDI_send, &ndi_video_frame);
            std::cout << "Successfully sent frame." << std::endl;
            total_frames_counter += 1;

            //free(ndi_video_frame.p_data);
            // Free the video frame
            // NDIlib_recv_free_video(pNDI_recv, &video_frame);
            //    free(ndi_video_frame.p_metadata);
        }

        // Just display something helpful
        printf("200 frames sent, at %1.2ffps\n", 200.0f / duration_cast<duration<float>>(high_resolution_clock::now() - start_send).count());
        cnt++;
    }

    // Destroy the NDI sender
    NDIlib_send_destroy(pNDI_send);

    // Not required, but nice
    NDIlib_destroy();

    // Success
    return 0;
}

