#include "webcam_test.h"

void WebcamTest::setup() {
  ofSetVerticalSync(true);
   _show_camera_input = true;
   _detect_faces = true;
   _ball_x = 0;
   _ball_y = 0;
  _webcam.setVerbose(true);
  _webcam.setDeviceID(0);
  _webcam.setDesiredFrameRate(30);
  _webcam.initGrabber(160, 120);
  _webcam.listDevices();
  _face_detector.setup("haarcascade_frontalface_default.xml");
}

void WebcamTest::update() {
  _webcam.update();
}

void WebcamTest::draw() {
  if (_show_camera_input) {
    _webcam.draw(0, 0);
  }
  if (_detect_faces) {
    _face_detector.findHaarObjects(_webcam.getPixelsRef());
    unsigned int face_count = _face_detector.blobs.size();
    ofPushStyle();
    ofNoFill();
    ofSetColor(0, 255, 0);
    if (_show_camera_input) {
      for (unsigned int i = 0; i < face_count; i++) {
        ofRectangle face = _face_detector.blobs[i].boundingRect;
        ofRect(face.x, face.y, face.width, face.height);
      }
    }
    if (face_count > 0) {
      ofSetColor(255, 0, 0);
      ofRectangle face = _face_detector.blobs[0].boundingRect;
      _ball_x = ofMap(face.x, 0, _webcam.getWidth(), 0, ofGetWidth());
      _ball_y = ofMap(face.y, 0, _webcam.getHeight(), 0, ofGetHeight());
      ofFill();
      ofCircle(_ball_x, _ball_y, 40);
    }
    ofPopStyle();
  }
}

void WebcamTest::keyPressed(int key) {
  if (key == 'c') {
    _show_camera_input = !_show_camera_input;
  } else if (key == 'f') {
    _detect_faces = !_detect_faces;
  }
}
