#include "picam_test.h"

void PicamTest::setup() {
  ofSetVerticalSync(true);
  _show_camera_input = true;
  _detect_faces = true;
  _ball_x = 0;
  _ball_y = 0;
  _pi_cam.setup(160, 120, 30);
  _fbo.allocate(_pi_cam.getWidth(), _pi_cam.getHeight(), GL_RGB);
  _frame.allocate(_pi_cam.getWidth(), _pi_cam.getHeight(), OF_PIXELS_RGB);
  _face_detector.setup("haarcascade_frontalface_default.xml");
}

void PicamTest::update() {
}

void PicamTest::draw() {
  ofPixels& pixels = getPixels();
  if (_pi_cam.isReady()) {
    if (_show_camera_input) {
      _pi_cam.draw();
    }
    if (_detect_faces) {
      _face_detector.findHaarObjects(pixels);
      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, _pi_cam.getWidth(), 0, ofGetWidth());
        _ball_y = ofMap(face.y, 0, _pi_cam.getHeight(), 0, ofGetHeight());
        ofFill();
        ofCircle(_ball_x, _ball_y, 40);
      }
      ofPopStyle();
    }
  }
}

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

ofPixels& PicamTest::getPixels() {
  _fbo.begin();
  _pi_cam.draw();
  _fbo.end();
  _fbo.readToPixels(_frame);
  return _frame;
}

