
#!/usr/bin/env python

import RPi.GPIO as GPIO, feedparser, time

import urllib2
import json
import time

import oauth, tweepy, sys, locale, threading 
from time import localtime, strftime, sleep

import max7219.led as led
device = led.sevensegment()

###### Gmail
DEBUG = 1

USERNAME = "xxxxxxxxxxxxxx"     # just the part before the @ sign, add yours here
PASSWORD = "**********"     

NEWMAIL_OFFSET = 1        # my unread messages never goes to zero, yours might
MAIL_CHECK_FREQ = 60      # check mail every 60 seconds

##################### gmail

GPIO.setmode(GPIO.BCM)



GREEN_LED = 1
RED_LED = 2
GPIO.setup(GREEN_LED, GPIO.OUT)
GPIO.setup(RED_LED, GPIO.OUT)



def gmail():
        global mail

        newmails = int(feedparser.parse("https://" + USERNAME + ":" + PASSWORD +"@mail.google.com/gmail/feed/atom")["feed"]["fullcount"])

        if DEBUG:
                print "You have", newmails, "new emails!"
                mail = newmails
        if newmails > NEWMAIL_OFFSET:
                GPIO.output(GREEN_LED, True)
                GPIO.output(RED_LED, False)
        else:
                GPIO.output(GREEN_LED, False)
                GPIO.output(RED_LED, True)

        #time.sleep(MAIL_CHECK_FREQ)
		
		
def get_page_data(page_id,access_token):
    api_endpoint = "https://graph.facebook.com/v2.4/"
    fb_graph_url = api_endpoint+page_id+"?fields=id,name,likes,unread_notif_count,unread_message_count,link&access_token="+access_token
    try:
        api_request = urllib2.Request(fb_graph_url)
        api_response = urllib2.urlopen(api_request)
        
        try:
            return json.loads(api_response.read())
        except (ValueError, KeyError, TypeError):
            return "JSON error"

    except IOError, e:
        if hasattr(e, 'code'):
            return e.code
        elif hasattr(e, 'reason'):
            return e.reason

			
def facebook():
    global like_count
    global notification_count
    page_id = "xxxxxxxxxxxxxxxx" # username or id https://developers.facebook.com/tools/explorer
    token = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"  # Access Token
    page_data = get_page_data(page_id,token)

    print "Page Name:"+ page_data['name']
    print "Likes:"+ str(page_data['likes'])
    like_count = page_data['likes']
    print "Link:"+ page_data['link']
    print "Unread notifications:"+ str(page_data['unread_notif_count'])
    notification_count = page_data['unread_notif_count']
    print "Unread message:"+ str(page_data['unread_message_count'])

    #time.sleep(0.5)

def twitter(): 
    global follower
    global api    #https://apps.twitter.com
    consumer_key = "xxxxxxxxxxxxxxxxxxxxxx"  # use your access key
    consumer_secret = "xxxxxxxxxxxxxxxxxxxxxxxxx"
    access_key = "xxxxxxxxxxxxxxxxxxxxxxxxxxxx"
    access_secret = "xxxxxxxxxxxxxxxxxxxxxxxxx"
    auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_key, access_secret)
    api = tweepy.API(auth)

    user = api.get_user(xxxxxxxxxx)  # your user id
    print user.screen_name
    print user.followers_count
    follower = user.followers_count
    print user.friends_count
    print user.favourites_count

def reverse(n):
    if(n<10):
	    return n*10
    else:
        return int(str(n)[::-1])	
	
def display():  # form a number from all information
    all_value = (reverse(follower) * 1000000) + (reverse(like_count)*10000) + (reverse(notification_count)*100) + reverse(mail) 
    print all_value
    device.write_number(deviceId=0, value=all_value)
	
while True:
        gmail()
        facebook()
        twitter()
        display()
        time.sleep(0.6)
    
