#include <opencv2/opencv.hpp>


cv::Rect box;
bool drawing_box = false;
int g_switch_value = 10;
void switch_off_function() { std::cout << "Pause "<<g_switch_value<<"\n"; }; //YOU COULD DO MORE
void switch_on_function() { std::cout << "Run "<<g_switch_value<<"\n"; };

// A little subroutine to draw a box onto an image
//
void draw_box(cv::Mat &img, cv::Rect box)
{
    cv::rectangle(
        img,
        box.tl(),
        box.br(),
        cv::Scalar(0x00, 0x00, 0xff)
        /* red */
    );
}

// This is our mouse callback. If the user
// presses the left button, we start a box.
// When the user releases that button, then we
// add the box to the current image. When the
// mouse is dragged (with the button down) we
// resize the box.
//
void my_mouse_callback(
    int event, int x, int y, int flags, void *param)
{
    cv::Mat image = *(cv::Mat *)param;
    switch (event)
    {
    case cv::EVENT_MOUSEMOVE:
    {
        if (drawing_box)
        {
            box.width = x - box.x;
            box.height = y - box.y;
        }
    }
    break;
        case cv::EVENT_LBUTTONDOWN:
        {
            drawing_box = true;
            box = cv::Rect(x, y, 0, 0);
        }
        break;
    case cv::EVENT_LBUTTONUP:
    {
        drawing_box = false;
        if (box.width < 0)
        {
            box.x += box.width;
            box.width *= -1;
        }
        if (box.height < 0)
        {
            box.y += box.height;
            box.height *= -1;
        }
        draw_box(image, box);
    }
    break;
    }
}

void switch_callback(int position, void *)
{
    if (position <= 5)
    {
        switch_off_function();
    }
    else
    {
        switch_on_function();
    }
}


int main(int argc, char **argv)
{
    box = cv::Rect(-1, -1, 0, 0);
    cv::Mat origin, image, temp;
    origin = cv::imread("./src/cv_test/src1.jpg");
    origin.copyTo(image);
    image.copyTo(temp);
    // image = cv::Scalar::all(0);
    cv::namedWindow("Box Example");

    cv::setMouseCallback(
        "Box Example",
        my_mouse_callback,
        (void *)&image);
    cv::createTrackbar(
        "Switch",
        "Box Example",
        &g_switch_value,
        20,
        switch_callback);

    for (;;)
    {
        image.copyTo(temp);
        if (drawing_box)
            draw_box(temp, box);
        if(!g_switch_value)
            origin.copyTo(image);
        cv::imshow("Box Example", temp);
        if (cv::waitKey(15) == 27)
            break;
    }
    return 0;
}