#!/usr/bin/python

# Shows profit of shares/bitcoin holdings and naturally, room temperature.

import max7219.led as led
import time, json, requests
from googlefinance import getQuotes
from datetime import datetime

# Holdings
tsla_qty = 10
tsla_invested = 1000.00
btc_qty = 10
btc_invested = 1000.00

# defs
def get_btc_usd():
        url = "http://api.coindesk.com/v1/bpi/currentprice.json"
        r = requests.get(url)
        results = r.json()
        btc_usd = results['bpi']['USD']['rate']
        btc_usd = btc_usd.replace(',', '')
        return btc_usd

def get_usd_gbp():
        url = "http://api.fixer.io/latest?base=USD"
        r = requests.get(url)
        results = r.json()
        usd_gbp_rate = results['rates']['GBP']
        return usd_gbp_rate

def workings(debug=False):
        usd_btc_rate = float(get_btc_usd())
        usd_gbp_rate = float(get_usd_gbp())
        try:
                tsla_data = getQuotes('TSLA')
        except NameError:
                print "Unable to get latest TSLA data..."
        tsla_usd = float(tsla_data[0]['LastTradePrice'])
        tsla_current_value = tsla_qty * tsla_usd * usd_gbp_rate
        tsla_gain = tsla_current_value - tsla_invested
        btc_current_value = btc_qty * usd_btc_rate * usd_gbp_rate
        btc_gain = btc_current_value - btc_invested
        total_gain = tsla_gain + btc_gain

        if debug == True:
                print "TSLA now: {} USD".format(tsla_usd)
                print "TSLA holdings current value GBP: {}".format(tsla_current_value)
                print "TSLA Gain GBP: {}".format(tsla_gain)

                print "BTC now {} USD".format(usd_btc_rate)
                print "BTC holdings current value GBP: {}".format(btc_current_value)
                print "BTC Gain GBP: {}".format(btc_gain)
                print "Total Gain GBP: {}".format(total_gain)
                print " "
        print "TSLA: {}, BTC: {}, USD: {}, Gain: {}".format(tsla_usd,usd_btc_rate,usd_gbp_rate,total_gain)
        print " "
        return total_gain

def clock(seg, seconds):
    """
    Display current time on device. Doesn't work.
    """
    interval = 0.5
    for i in range(int(seconds / interval)):
        now = datetime.now()
        seg.text = now.strftime("%H-%M-%S")

        # calculate blinking dot
        if i % 2 == 0:
            seg.text = now.strftime("%H-%M-%S")
        else:
            seg.text = now.strftime("%H %M %S")
        time.sleep(interval)

def get_temp():
        tempfile = open("/sys/bus/w1/devices/28-031561fbfaff/w1_slave")
        thetext = tempfile.read()
        tempfile.close()
        tempdata = thetext.split("\n")[1].split(" ")[9]
        temp = float(tempdata[2:])
        temp = temp/1000
        return temp

def flash_led(num):
        for i in range(0,3):
                device.clear(0)
                time.sleep(0.5)
                device.write_number(deviceId=0, value=num, zeroPad=False, decimalPlaces=2)
                time.sleep(0.5)

def fadeout_led():
        for i in range(7,0,-1):
            device.brightness(i)
            time.sleep(0.2)
        device.clear()
        time.sleep(0.2)
        device.brightness(7)

def output_to_led(num, temp):
        for i in range(1,6):
                device.write_number(deviceId=0, value=temp, zeroPad=False)
                time.sleep(3)
                device.write_number(deviceId=0, value=num, zeroPad=False, decimalPlaces=2)
                flash_led(num)
                time.sleep(7)

# main
device = led.sevensegment()
while True:
        print "getting updated data..."
        temp = get_temp()
        num = workings(debug = True)
        output_to_led(num,temp)
