#!/usr/bin/python
import RPi.GPIO as GPIO
import time
import datetime
import sys
import gspread

GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) # "A" Button Flush Sensor
GPIO.setup(23, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) # "B" Button TP R&R Sensor

# Google Acoount Details
email = 'nnnnnnnnn@gmail.com'
password = 'xxxxxxxx'
spreadsheet = 'Potty_Logger'

# Login with your Google account
try:
  gc = gspread.login(email, password)
except:
  print "unable to login in. Check your email address/password"
  sys.exit()
  
# Open a worksheet for your spreadsheet using the filename
try:
  wks = gc.open(spreadsheet).sheet1
except:
  print ("unable to open the spredsheet.  Check your filename: %s") % spreadsheet
  sys.exit()

time.sleep(1)
  
while True:
    flush_state = GPIO.input(18)
    tp_state = GPIO.input(23)
	# code assumes flushing and TP R&R don't occur at the same time, key fob can't send two button presses at once
    if flush_state == True:
        print('flushed')
	print(datetime.datetime.now(), "Flushed")
	print('write flushed event data to gdocs')
	try:
           values = [datetime.datetime.now(), "Flushed"]
           wks.append_row(values)
        except:
           print ("Unable to append data.  Check your connection?")
           sys.exit()  
        # wait 60 seconds for flushing to finish
        time.sleep(60)
    if tp_state == True:
        print('TP R&R')
	print(datetime.datetime.now(), "TP R&R")
	print('write TP R&R event data to gdocs')
	try:
           values = [datetime.datetime.now(), "TP R&R"]
           wks.append_row(values)
        except:
           print ("Unable to append data.  Check your connection?")
           sys.exit()  
        # wait 120 seconds for TP R&R task to finish
        time.sleep(120)




