#include "input.h"

// TODO: Wenn ihr in die Zeile den Pfad zum Testvideo statt der 0 packt, benmutzt er das Testvideo.
Input::Input(int videoHeight, int videoWidth) : cap("C:\\Line-Following-Robot\\AutonomousMode\\Test_data\\video1.h264"), videoHeight(videoHeight), videoWidth(videoWidth)//Input::Input(int videoHeight, int videoWidth) : cap(0), videoHeight(videoHeight), videoWidth(videoWidth)
//Input::Input(int videoHeight, int videoWidth) : cap(0), videoHeight(videoHeight), videoWidth(videoWidth)
{
    std::unique_lock<std::mutex> lock(mtx);
    this->cap.set(CAP_PROP_FRAME_HEIGHT, videoHeight);
    this->cap.set(CAP_PROP_FRAME_WIDTH, videoWidth);
}

Input::~Input()
{
    this->freeWebcam();
}

Mat Input::readFile(String filePath)
{
    std::unique_lock<std::mutex> lock(mtx);
    std::srand(static_cast<unsigned int>(std::time(0)));
    // Read all .jpg files from the specified folder
    cv::String folder = filePath;
    std::vector<cv::String> filenames;
    cv::glob(folder, filenames);

    // Random shuffle
    std::random_device rd;
    std::mt19937 g(rd());
    std::shuffle(filenames.begin(), filenames.end(), g);

    Mat image = imread(filePath, IMREAD_COLOR);
    
    if(image.empty())
    {
        stringstream sstream;
        sstream << "Could not read the image: " << filePath << std::endl;
        throw std::runtime_error(sstream.str());
    }
    resize(image, image, Size(this->videoWidth, this->videoHeight));
    return image;
}

Mat Input::readWebcam()
{
    std::unique_lock<std::mutex> lock(mtx);
    Mat image;

    if(!cap.isOpened()) {
        stringstream sstream;
        sstream << "Video capture not opened" << std::endl;
        throw std::runtime_error(sstream.str());
    }

    if(!cap.grab()) {
        stringstream sstream;
        sstream << "Could not grab frame from camera" << std::endl;
        throw std::runtime_error(sstream.str());
    }   
    cap.retrieve(image);
    return image;  
}

void Input::freeWebcam()
{
    std::unique_lock<std::mutex> lock(mtx);
    this->cap.release();
}
