import RPi.GPIO as GPIO
import time

"""
Explanation: GPIO Listening to Buttons!
First order of business is to import some libraries to help send/receive signals to/from the GPIO pins of the Raspberry Pi.
End of explanation
"""


GPIO.setmode(GPIO.BCM)
outpin = 25
GPIO.setup(outpin, GPIO.OUT)

"""
Explanation: The following code will set the mode to a Broadcom pin layout (which seems to be what we want).  We'll also go ahead and set up the LED output pin.
End of explanation
"""


inpin = 18
GPIO.setup(inpin, GPIO.IN, pull_up_down=GPIO.PUD_UP) # the pull_up_down keeps us from worrying about pull-up resistors

prev_input = 1 # looking for a 'False' as the button press signal, so we start with a "True"
while True:
    #take a reading
    input = GPIO.input(inpin)
    #if the last reading was low and this one high, print
    if ((not prev_input) and input):
        print("Button pressed")
    #update previous input
    prev_input = input
    #slight pause to debounce
    time.sleep(0.05)

"""
Explanation: Buttons
Buttons require us to 'listen' indefinitely for input to our GPIO pin.  We use an infinite loop to do this.  To stop the loop, you simply click Kernel/Interrupt in the menu above.
Once the button is wired to the pin designated below (inpin #) with the appropriate resistors, set up the port as an input port:
End of explanation
"""


from picamera import PiCamera, Color
from time import sleep

"""
Explanation: So, now let's do something with that button press -- how about flashing our light, then taking a photo.
We'll first import the camera class...
End of explanation
"""


def blink_and_shoot(idx):
    """ idx: an index number for photos to be stored at /img/snapshot-[idx] """
    
    # set up camera
    with PiCamera() as camera:
        #camera.resolution = (480, 320)  # uncomment this line if you want smaller photos
        camera.vflip = True
        camera.hflip = True
        camera.start_preview()

        for i in range(3):
            GPIO.output(outpin, True)
            time.sleep(0.2)
            GPIO.output(outpin, False)

        #camera.image_effect = 'oilpaint' # just to make things interesting
        sleep(0.5)
        camera.capture('img/snapshot-%s.jpg' % idx)
        camera.stop_preview()


"""
Explanation: We'll wait to instantiate our camera object, just so we don't crash anything with a bunch of button presses.
End of explanation
"""


prev_input = 1 # looking for a 'False' as the button press signal, so we start with a "True"
counter = 1
while True:
    #take a reading
    input = GPIO.input(inpin)
    #if the last reading was low and this one high, print
    if ((not prev_input) and input):
        print("Taking photo%s" % counter)
        blink_and_shoot(counter)
        counter += 1
    #update previous input
    prev_input = input
    #slight pause to debounce
    time.sleep(0.05)

GPIO.cleanup()

"""
Explanation: Now for the infinite button loop to listen for a press:
End of explanation
"""


