#!/usr/bin/python
#based on this https://gist.github.com/larsks/6161684

#import pifacecommon.core
import pifacecommon.interrupts
import os
import time
import pifacecad
import pycurl
import StringIO
import textwrap
import string
import re

page = 0
maxPage = 0
quit = False
split_quote = ['---']

def print_flag(event):
    print 'You pressed button', event.pin_num, '.'

def get_quote_button(event):
    global page
    global split_quote
    split_quote = get_quote()
    page=0
    print_page(split_quote,page)

def page_next(event): # display the next 2 lines of quote
    global page
    global split_quote
    global maxPage
    if page+2 > maxPage:  # don't go past the end
      page = maxPage
    else:
      page = page + 2
    print_page(split_quote,page)

def page_back(event):  # redisplay the previous part of quote
    global page
    global split_quote
    if page > 2:
      page = page -2
    else:
      page = 0
    print_page(split_quote,page)
    page = page 

def stop_listening(event):
    global quit
    quit = True

def get_quote():
    global maxPage
    c = pycurl.Curl()
# Get text version of a quote, we are getting one-liners, but other source types
# are available such as fortune and famousquotes, see iheartquotes.com    
    c.setopt(c.URL, 'http://iheartquotes.com/api/v1/random?source=oneliners')
    contents = StringIO.StringIO()
    c.setopt(c.WRITEFUNCTION, contents.write)
    c.perform()
    lineout = contents.getvalue()
    lineout = re.sub(r'&quot','"',lineout)
# Remove the last section of the data...refers to the source webpage
    lineout = re.sub(r'\[oneliners.*','',lineout)
    formatted_text = textwrap.fill(lineout,width=16)
    splitted = string.split(formatted_text, '\n')
    if bool(len(splitted) % 2):
      # odd number so add a line to make it even or we would page off end
      splitted.append("----")
    maxPage = len(splitted)
    return splitted

def print_page(splitted,page):
    cad.lcd.home
    cad.lcd.clear()
    if page < maxPage:
        print splitted[page]
        cad.lcd.write(splitted[page])
        cad.lcd.write("\n")
	print splitted[page+1]
        cad.lcd.write(splitted[page+1])


cad = pifacecad.PiFaceCAD()
# this is the text to be left off the results from iheartquotes
#p = re.compile('\[oneliners*')  # regular expression for sources

listener = pifacecad.SwitchEventListener(chip=cad)

# set up listeners for all buttons including the CAD Rocker
listener.register(0, pifacecommon.interrupts.IODIR_ON, page_back)
listener.register(1, pifacecommon.interrupts.IODIR_ON, page_next)
listener.register(2, pifacecommon.interrupts.IODIR_ON, get_quote_button)
listener.register(3, pifacecommon.interrupts.IODIR_ON, stop_listening)
listener.register(4, pifacecommon.interrupts.IODIR_ON, print_flag)
listener.register(5, pifacecommon.interrupts.IODIR_ON, print_flag)
listener.register(6, pifacecommon.interrupts.IODIR_ON, print_flag)
listener.register(7, pifacecommon.interrupts.IODIR_ON, print_flag)
#listener.register(KEY_1,pifacecommon.interrupts.IODIR_ON, print_flag)

# Start listening for events.  This spawns a new thread.
listener.activate()
cad.lcd.backlight_on()

split_quote = get_quote()
print_page(split_quote,page)

# Hang around until someone presses button 3.
while not quit:
    time.sleep(1)

print 'Thank you and good night - button 3 (quitting)'
cad.lcd.write("Bye!\n")

cad.lcd.home
cad.lcd.clear()
cad.lcd.backlight_off()
listener.deactivate()