import os
from datetime import datetime
import io
import picamera
import subprocess


secs_before = 10
video_path = 'Videos/'
trigger_fileextension = '.trg'
trigger_path = 'trigger/'
triggerfile = ''
triggered = False

# Format of trigger file name:          2016-08-26-08-05-00.trg

# Look for remote trigger file
def detect_trigger(camera):
  global triggerfile, triggered
  dir = subprocess.Popen(['ssh','pi@192.168.1.20','ls', trigger_path],
                         stdout=subprocess.PIPE,
                         stderr=subprocess.PIPE,
                         universal_newlines=True)
  try:
    out, err = dir.communicate(timeout=5)
  except subprocess.TimeoutExpired:
    dir.kill()
    out = ""
    err = "Timeout"
  if err != "":
    print("out :{0}: err :{1}:".format(out, err))
# on communication error return current status
    return triggered
  triggerfiles = [f for f in out.splitlines() if f.endswith(trigger_fileextension)]
  if not triggered:
# Not triggered before - look for trigger file
    if triggerfiles:
# Trigger file detected, trim file extension
      triggerfile = triggerfiles[0].split('.')[0:1][0]
      triggered = True
      print('Trigger detected!')
      print(triggerfile)
      return True
    else:
      return False
  else:
# Trigger already active - check whether trigger file ist still present
    if (triggerfile + trigger_fileextension) in triggerfiles:
      return True
    else:
      triggered = False
      return False

with picamera.PiCamera() as camera:
  camera.resolution = (1920, 1080)
  camera.framerate = 25
#  camera.hflip = True
#  camera.vflip = True
  stream = picamera.PiCameraCircularIO(camera, seconds=(secs_before+10))
  camera.start_recording(stream, format='h264')
# Fill ringbuffer
  print('Ready for trigger')
  try:
    while True:
      camera.wait_recording(1)
      if detect_trigger(camera):
# Convert filename to datetime object
        triggertime = datetime.strptime(triggerfile, '%Y-%m-%d-%H-%M-%S')
# Calc seconds to fetch from ringbuffer
        currenttime = datetime.now()
        if triggertime > currenttime:
          triggertime = currenttime
        beforetime = (currenttime - triggertime).total_seconds() + secs_before
        print(beforetime)
# As soon as we detect trigger, split the recording to record the frames "after" trigger
        camera.split_recording(video_path + 'a-' + triggerfile + '.h264')
# Write the seconds "before" motion to disk as well
        stream.copy_to((video_path + 'b-' + triggerfile + '.h264'), seconds=beforetime)
        stream.clear()
# Wait for file to disappear, then split recording back to the in-memory circular buffer
        while detect_trigger(camera):
          camera.wait_recording(1)
        print('Trigger stopped!')
        camera.split_recording(stream)
# Start postprocessing
        print('Connect files')
        postprocess = 'python3 postprocess.py '+video_path+' '+triggerfile+' &'
        os.system(postprocess)
  finally:
    camera.stop_recording()