#include <iostream>
#include <opencv2/opencv.hpp>
#include "src/Detector.hpp"

using namespace cv;
using namespace std;


// List of points
typedef vector<Point> contour_t;
// List of contours
typedef vector<contour_t> contour_vector_t;

Mat videoStreamFrameGray;
Mat videoStreamFrameOutput;

// Pos is from UI, dereferencing of the pointer
static void on_trackbar(/* ??? */) {
  //*((???*)???) = ???;
}

int main() {

  Mat frame;
  VideoCapture cap(0);

  if (!cap.isOpened()) {
    cout << "No webcam, using video file" << endl;
    cap.open("MarkerMovie.MP4");
    if (cap.isOpened() == false) {
      cout << "No video!" << endl;
      exit(0);
    }
  }

  const string contoursWindow = "Contours";
  const string thresholdWindow = "Threshold";

  namedWindow(contoursWindow, WINDOW_AUTOSIZE);
  namedWindow(thresholdWindow, WINDOW_AUTOSIZE);

  const string UI = "Threshold";
  int threshold = 65;
  createTrackbar(UI, thresholdWindow, &threshold, 255);


  Mat imgFiltered;
  Detector detector;

  //VIDEO
  //VideoWriter threshOut("threshold.avi", VideoWriter::fourcc('M', 'J', 'P', 'G'), 24, Size(cap.get(3), cap.get(4)));
  //VideoWriter imgOut("makerDetection.avi", VideoWriter::fourcc('M', 'J', 'P', 'G'), 24, Size(cap.get(3), cap.get(4)));


  while (cap.read(frame)) {

    // --- Process Frame ---
    Mat grayScale;
    imgFiltered = frame.clone();
    cvtColor(imgFiltered,grayScale, COLOR_BGR2GRAY);

    // Threshold to reduce the noise
    adaptiveThreshold(grayScale, grayScale, 255, ADAPTIVE_THRESH_MEAN_C, THRESH_BINARY, 45, 15);
    cv::threshold(grayScale, videoStreamFrameGray, threshold, 255, THRESH_OTSU);

    detector.detect(videoStreamFrameGray, imgFiltered);

    imshow(contoursWindow, imgFiltered);
    imshow(thresholdWindow, videoStreamFrameGray);

    //VIDEO
    //threshOut.write(videoStreamFrameGray);
    //imgOut.write(imgFiltered);

    if (waitKey(10) == 27) {
      break;
    }
  }

  cap.release();

  //VIDEO
  //threshOut.release();
  //imgOut.release();

  destroyAllWindows();

  return (0);
}
