#!/usr/bin/env python

import picamera
import fcntl
from time import sleep, time, strftime

import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setup(4, GPIO.IN, GPIO.PUD_UP)
GPIO.add_event_detect(4, GPIO.FALLING)
GPIO.setup(25, GPIO.IN, GPIO.PUD_UP)
GPIO.add_event_detect(25, GPIO.FALLING)
GPIO.setup(8, GPIO.OUT, initial=0)
GPIO.setup(7, GPIO.OUT, initial=0)
GPIO.setup(32, GPIO.OUT, initial=False)
imagecount = 0

with picamera.PiCamera() as camera:
    camera.resolution = (1024, 768)
    GPIO.output(32, True)
    sleep(2)
    GPIO.output(32, False)
    try:
        while True:
            if GPIO.event_detected(25):
                GPIO.output(7, True)
                global imagecount
                filename = ('/home/pi/cache/image{'+ strftime('%Y-%m-%d-%H-%M') +'}'+ str(imagecount) +'.jpg')
                imagecount = imagecount +1
                sleep(5)
                camera.capture(filename)
                sleep(5)
                GPIO.output(7, False)
                GPIO.output(32, True)
                sleep(2)
                filename = ('/home/pi/cache/image{'+ strftime('%Y-%m-%d-%H-%M') +'}'+ str(imagecount) +'.jpg')
                imagecount = imagecount +1
                GPIO.output(32, False)
                GPIO.output(8, True)
                sleep(5)
                camera.capture(filename)
                sleep(5)
                GPIO.output(8, False)
                GPIO.output(32, True)
                sleep(5)
                GPIO.output(32, False)
    except KeyboardInterrupt:
        pass
    finally:
        GPIO.cleanup()
