#!/usr/bin/python

import picamera
import datetime as dt
import signal
import time
import sys
import RPi.GPIO as GPIO
import os
import thread

LED_PIN = 14
HALT_PIN = 15

# Shutdown callback for halting the system
def Shutdown(channel):
  os.system("shutdown -h now")

# Setting up GPIO pins for LED and push-down button
GPIO.setmode(GPIO.BCM)
GPIO.setup(HALT_PIN, GPIO.IN, pull_up_down = GPIO.PUD_UP)
GPIO.add_event_detect(HALT_PIN, GPIO.FALLING, callback = Shutdown, bouncetime = 2000)
GPIO.setup(LED_PIN, GPIO.OUT)

# Class for handling SIGTERM signal in order to gracefully stopping the camera.
class GracefulKiller:
  kill_now = False
  def __init__(self):
    signal.signal(signal.SIGINT, self.exit_gracefully)
    signal.signal(signal.SIGTERM, self.exit_gracefully)

  def exit_gracefully(self,signum, frame):
    self.kill_now = True

def RunCamera(argv, killer):
  time_len = int(argv[1])
  segment_len = int(argv[2])
  with picamera.PiCamera() as camera:
    camera.resolution = (1360, 768)
    camera.framerate = 24
    camera.brightness = 60
    camera.contrast = 20
    camera.sharpness = 20
    camera.annotate_foreground = picamera.Color('black')
    camera.annotate_background = picamera.Color('white')
    camera.annotate_text = dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    camera.annotate_text_size = 22
    zero = dt.datetime.now()
    while (dt.datetime.now() - zero).seconds <= time_len:
      start = dt.datetime.now()
      file_name = start.strftime('/home/pi/camera/%Y%m%d-%H%M%S.h264')
      print 'Record: ' + file_name
      camera.start_recording(file_name, bitrate=4500000)
      now = dt.datetime.now()
      while ((now - start).seconds <= segment_len) and ((now - zero).seconds <= time_len):
        camera.annotate_text = dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        camera.wait_recording(1)
        now = dt.datetime.now()
        if killer.kill_now:
          camera.stop_recording()
          return
      camera.stop_recording()

def ToggleLED():
	LED_ON=True
	while True:
		if LED_ON:
			GPIO.output(LED_PIN, GPIO.LOW)
			LED_ON = False
		else:
			GPIO.output(LED_PIN, GPIO.HIGH)
			LED_ON = True
		time.sleep(1)

if __name__ == "__main__":
	thread.start_new_thread(ToggleLED, ())

	killer = GracefulKiller()
	RunCamera(sys.argv, killer)

