#include "aquarium_monitor.h"
#include "temp_sensor.h"

void AquariumMonitor::setup() {
  ofSetVerticalSync(true);
  ofHideCursor();
  _elapsed_time = ofGetElapsedTimeMillis();
  _show_info = false;
  _screen_counter = 1;
  ofTrueTypeFont::setGlobalDpi(72);
  _verdana.loadFont("verdana.ttf", 30, true, true);
  _verdana.setLineHeight(34.0f);
  _verdana.setLetterSpacing(1.035);
  _mono.loadFont("mono.ttf", 30, true, true);
  _mono.setLineHeight(34.0f);
  _mono.setLetterSpacing(1.035);
  get_temperature();
  _pi_cam.setup(1024, 768, 30);
  _fbo.allocate(_pi_cam.getWidth(), _pi_cam.getHeight(), GL_RGB);
  _frame.allocate(_pi_cam.getWidth(), _pi_cam.getHeight(), OF_PIXELS_RGB);
}

void AquariumMonitor::update() {
  unsigned long long current_time = ofGetElapsedTimeMillis();
  if (current_time - _elapsed_time >= 60 * 1000) {
    _elapsed_time = current_time;
    get_temperature();
  }
}

void AquariumMonitor::draw() {
  getPixels();
  if (_pi_cam.isReady()) {
    _pi_cam.draw();
  }
  ofEnableAlphaBlending();
  ofSetColor(255, 255, 255, 200);
  _verdana.drawString(std::string("Wassertemperatur: ") + std::string(_current_temp), 30, 35);
  std::string format_string = "%H:%M";
  if (ofGetSeconds() % 2) {
    format_string = "%H %M";
  }
  _mono.drawString(ofGetTimestampString(format_string), 870, 35);
  show_info();
  ofDisableAlphaBlending();
}

void AquariumMonitor::keyPressed(int key) {
  if (key == 's') {
    ofImage screenshot;
    screenshot.grabScreen( 0, 0, ofGetWidth(), ofGetHeight());
    screenshot.saveImage(std::string("screen") + ofToString(_screen_counter++) + std::string(".bmp"));
  } else if (key == 'i') {
    _show_info = !_show_info;
  }
}

void AquariumMonitor::get_temperature() {
  strcpy(_current_temp, "21.1");
  return;
  TemperatureSensor temp_sensor("/sys/bus/w1/devices/28-000004f21649/w1_slave");
  sprintf(_current_temp, "%.1f C", temp_sensor.get_temperature());
}

void AquariumMonitor::show_info() {
  if (_show_info) {
    ofFill();
    ofRectRounded(212, 183, 600, 400, 10);
    ofSetColor(100, 100, 100, 255);
    int x = 230;
    int y = 240;
    _verdana.drawString("Eingerichtet am 30.11.2013.", x, y);
    y += 60;
    _verdana.drawString("Aktueller Besatz:", x, y);
    y += 60;
    _verdana.drawString("Zwei Geweihschnecken.", x, y);
    y += 30;
    _verdana.drawString("Zwei rote Rennschnecken.", x, y);
    y += 60;
    _verdana.drawString("Beleuchtungszeit: 8 Uhr - 17 Uhr", x, y);
  }
}

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

