
#!/usr/bin/env
# This is the main pipecam software
import os
import json
#import picamera # comment out for dev
from time import gmtime, strftime
#import RPi.GPIO as GPIO # comment out for dev

################################################################################################################################

def healthCheck():
	# Here we collect some stats on the overall health
	print "beep"

def takePhoto(path):
	# Here we handle taking a photo
	timestamp =  strftime("%d-%m-%YH%H%M%S", gmtime())
	extention = ".jpg"
	file_name = path +"/pipecam/photo/"+ timestamp + extention

	# camera.capture(file_name)
	#file_name = path +"/pipecam/photo/"+ timestamp
	#cmd = "raspistill -hf -vf -ex beach -t 30000 -tl 500 -o %s%04d%s" % (file_name, extention)
	cmd = "raspistill -hf -vf -ex beach -o %s" % file_name
	os.system(cmd)

def takeVideo(path):
	# Here we handle taking a photo
	timestamp =  strftime("%d-%m-%YH%H%M%S", gmtime())
	extention = ".h264"
	file_name = path +"/pipecam/video/"+ timestamp + extention
	# Settings https://www.npmjs.com/package/raspivid
	w = '-w 1920'		  			# -w, --width     			: Set image width <size>. Default 1920
	h = '-h 1080' 					# -h, --height    			: Set image height <size>. Default 1080
	ex = ''							# -ex, --exposure 			: Set exposure mode options: auto,night,nightpreview,backlight,spotlight,sports,snow,beach,verylong,fixedfps,antishake,fireworks
	t = '-t 900000' 				# -t, --timeout  		 	: Time (in ms) to capture for. If not specified, set to 5s. Zero to disable
	fps = '' 						# -fps, --framerate       	: Specify the frames per second to record


	#cmd = "raspivid %s -vf %s %s %s -o %s.h264 " %(t,ex,w,h,file_name)
	cmd = "raspivid -t 280000 -vf -ex beach -w 1280 -h 720 -o %s" %file_name
	os.system(cmd)


# Create an object class for each drive
class StorageDrive:
	def __init__(self,name,path):

		self.name = name
		self.path = path
		# Try to open the USB drives, if you cannot open the drive, mark as not present and set size availabe as 0
		try:
			usb = os.statvfs(path)
			self.space = (usb.f_frsize * usb.f_bfree)/1024/1024
			self.present = 1
		except:
			self.space = 0
			self.present = 0


################################################################################################################################

# Start here
mode = 1 # 0 for photo 1 for video									# Set the mode of the pipecam. 0 for photos, 1 for videos

# # Set up the GPIO
# mode_pin = 17
# GPIO.setup(17, GPIO.IN) 					# Pull down to be set up in hardware
# # If the slider switch was set, set the camera into video mode.
# if GPIO.input(17):
# 	mode = 1


# Define the drive objects
local = StorageDrive('root','/')
usb = []
usb.append(StorageDrive('usb1','/mnt/usb1'))
usb.append(StorageDrive('usb2','/mnt/usb2'))
usb.append(StorageDrive('usb3','/mnt/usb3'))
usb.append(StorageDrive('usb4','/mnt/usb4'))

# Set the home path where files are stored onboard
local_path = "/home/pi"


# Decide where to save the files first, extrenal drive or on board SD
save_on_removable = 1 						# Record on external drives by default (1)
minimun_space = 30 						# What is the minimum space in MB which can be considered for recording

# create a list of available drives
availableDrives = [u for u in usb if u.space > minimun_space]
# if the amount of available drives is 0, do not try to save on the external
save_on_removable = 0 if len(availableDrives) == 0 else 1

# Check if local space is full and all drives are full. quit the script and write a message to the user in the status file
if local.space < minimun_space and availableDrives == 0:
	print "All drives are full"
	os.system('echo "All drives are full" >> /home/pi/status')
	sys.exit()

# Set the destination path
if save_on_removable == 1 and len(availableDrives) != 0:
	# if set to save on removable drive and there is space available, then set the destination path to the first available drive
	path = availableDrives[0].path
else:
	path = local_path

timestamp =  strftime("%d-%m-%YH%H%M%S", gmtime())
# Now lets take some video/photos
if mode == 0:
	print "%s: taking photo on %s" % (timestamp,path)
	takePhoto(path)
else:
	print "%s: taking video %s" % (timestamp,path)
	takeVideo(path)
