# Python 2.7.1

import RPi.GPIO as GPIO
from twython import Twython
import time
import sys
import os
import pygame

APP_KEY='zmmlyAJzMDIntLpDYmSH98gbw'
APP_SECRET='ksfSVa2hxvTQKYy4UR9tjpb57CAynMJDsygz9qOyzlH24NVwpW'
OAUTH_TOKEN='794094183841566720-BagrHW91yH8C3Mdh9SOlBfpL6wrSVRW'
OAUTH_TOKEN_SECRET='d0Uucq2dkSHrFHZGLM1X8Hw05d80ajKYGl1zTRxZQSKTm'
applepislcy = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)

### GENERAL ###

def Cleanup():
    GPIO.cleanup()

def Sleep(seconds):
    """Puts the program to sleep"""
    time.sleep(seconds)

def Alert(channel):
    """Simple alert function for testing event interrupts"""
    print('Alert on channel',channel)

def TimeString():
    """Returns the current time"""
    t = time.localtime()
    return str(t[0])+'.'+str(t[1])+'.'+str(t[2])+'.'+str(t[3])+'.'+str(t[4])+'.'+str(t[5])

def LoadPins(mapping,inp):
    """Organizes an input into a pin mapping dict
    mapping <list>, ['IA','IB']
    inp <dict>, <list>, <int> {'IA':1,'IB':2}, [1,2]
    """
    if type(inp) is int and len(mapping) == 1:
        return {mapping[0]:inp}
    elif type(inp) is list and len(mapping) == len(inp):
        o = {}
        for i in range(len(inp)):
            o[mapping[i]] = inp[i]
        return o
    elif type(inp) is dict:
        return inp
    else:
        print('Invalid input for pins:',inp,type(inp))
        print('Expected:',mapping)
        return {}

def BoolToSign(inp):
    """Converts boolean bits into signed bits
    0 -> -1
    1 -> 1"""
    return (inp * 2) - 1

def SignToBool(inp):
    """Converts signed bits into boolean bits
    -1 -> 0
    1 -> 1"""
    return (inp + 1) / 2

### PYGAME ###

def WindowSetup(size=(300,50),caption='',text='',background=(0,0,0),foreground=(255,255,255)):
    """Sets up a pygame window to take keyboard input
    size <tuple>, width by height
    caption <str>, window title bar
    text <str>, text to display in window, accepts \n
    background <tuple>, foreground <tuple>, (r,g,b) color
    """
    pygame.init()
    screen = pygame.display.set_mode(size,0,32)
    pygame.display.set_caption(caption)
    myfont = pygame.font.SysFont('Monospace',15)
    labels = []
    lines = text.split('\n')
    for line in lines:
        labels.append(myfont.render(line,1,foreground))
    screen.fill(background)
    y = 0
    for label in labels:
        screen.blit(label, (0,y))
        y += 15
    pygame.display.update()

def InputLoop(eventmap):
    """Begins a pygame loop, mapping key inputs to functions
    eventmap <dict>, {pygame.K_t:myfunction}
    """
    index = 0
    while True:
        events = pygame.event.get()
        for event in events:
            if event.type == pygame.KEYDOWN:
                #print("{0}: You pressed {1:c}".format ( index , event.key ))
                if event.key in eventmap:
                    eventmap[event.key]()
            elif event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()

def InputLoopDemo():
    def dog():
        print('woof')
    def cat():
        print('meow')
    def fish():
        print('blub')
    WindowSetup(caption='pet simulator',text='d for dog\nc for cat\nf for fish')
    InputLoop({pygame.K_d:dog, pygame.K_c:cat, pygame.K_f:fish})

### TWITTER ###

def Tweet(twit,statustext):
    """Tweets a message
    twit <Twython>, create with Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
    statustext <str>, must be <= 140 characters
    """
    if len(statustext) > 140:
        print('ERROR: Character limit 140 exceeded:',len(statustext))
    else:
        twit.update_status(status=statustext)

def TweetPicture(twit,file,statustext):
    """Tweets a message with a picture
    twit <Twython>, create with Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
    file <str>, path and filename to picture
    statustext <str>, must be <= 140 characters
    """
    photo = open(file, 'rb')
    response = twitter.upload_media(media=photo)
    twit.update_status(status=statustext, media_ids=[response['media_id']])

def TweetVideo(twit,file,statustext):
    """Tweets a message with a video
    twit <Twython>, create with Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
    file <str>, path and filename to video
    statustext <str>, must be <= 140 characters
    """
    video = open(file, 'rb')
    response = twitter.upload_video(media=video, media_type='video/mp4')
    twit.update_status(status=statustext, media_ids=[response['media_id']])

[((14, 14, 14, 75), 'twython.Twython', 'Twython', ({(14, 22, 14, 29): 'APP_KEY', (14, 31, 14, 41): 'APP_SECRET', (14, 43, 14, 54): 'OAUTH_TOKEN', (14, 56, 14, 74): 'OAUTH_TOKEN_SECRET'}, {}), '(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)', False, 'from twython import Twython\n'), ((19, 4, 19, 18), 'RPi.GPIO.cleanup', 'GPIO.cleanup', ({}, {}), '()', True, 'import RPi.GPIO as GPIO\n'), ((23, 4, 23, 23), 'time.sleep', 'time.sleep', ({(23, 15, 23, 22): 'seconds'}, {}), '(seconds)', False, 'import time\n'), ((31, 8, 31, 24), 'time.localtime', 'time.localtime', ({}, {}), '()', False, 'import time\n'), ((74, 4, 74, 17), 'pygame.init', 'pygame.init', ({}, {}), '()', False, 'import pygame\n'), ((75, 13, 75, 47), 'pygame.display.set_mode', 'pygame.display.set_mode', ({(75, 37, 75, 41): 'size', (75, 42, 75, 43): '0', (75, 44, 75, 46): '32'}, {}), '(size, 0, 32)', False, 'import pygame\n'), ((76, 4, 76, 39), 'pygame.display.set_caption', 'pygame.display.set_caption', ({(76, 31, 76, 38): 'caption'}, {}), '(caption)', False, 'import pygame\n'), ((77, 13, 77, 48), 'pygame.font.SysFont', 'pygame.font.SysFont', ({(77, 33, 77, 44): '"""Monospace"""', (77, 45, 77, 47): '15'}, {}), "('Monospace', 15)", False, 'import pygame\n'), ((87, 4, 87, 27), 'pygame.display.update', 'pygame.display.update', ({}, {}), '()', False, 'import pygame\n'), ((95, 17, 95, 35), 'pygame.event.get', 'pygame.event.get', ({}, {}), '()', False, 'import pygame\n'), ((102, 16, 102, 29), 'pygame.quit', 'pygame.quit', ({}, {}), '()', False, 'import pygame\n'), ((103, 16, 103, 26), 'sys.exit', 'sys.exit', ({}, {}), '()', False, 'import sys\n')]