import requests
import sys
import colorsys

######################
#Configuration constants
DAILY_STD_DEV  = 1.120             #In %, what is the standard deviation of stock price change?
CALL_FREQUENCY = 5                 #How often this script will be called, in minutes
STOCK_TO_TRACK = '.dji'

GOOD_HUE       = 120		   #Default is green
BAD_HUE        = 0                 #Default is red

SELECTOR       = "group:StockOrb" #Which light to use

######################
verbose = False
if(len(sys.argv[1:]) > 0 and sys.argv[1] == "-v"):
    verbose = True
    print "Executing in verbose mode"

getresponse = requests.get("https://www.google.com/finance?q="+STOCK_TO_TRACK)
if(getresponse.status_code != 200):
    print "Loading stock data failed"
    sys.exit(0)

start_of_price_change = getresponse.text.find("id-price-change")
trimmed = getresponse.text[start_of_price_change:start_of_price_change+200]
if(verbose):
    print trimmed
    
start_of_pct = trimmed.find("(")
end_of_pct = trimmed.find("%")
pct_str = trimmed[start_of_pct+1:end_of_pct]
if(verbose):
    print pct_str

pct_change = float(pct_str);
if(verbose):
    print "pct_change: " + str(pct_change)

######################
#Set up the auth header
f = open('token.txt', 'r')
token = f.readline()
headers = {
    "Authorization": "Bearer %s" % token.rstrip(),
}

############################
#Calculate color from pct_change

#very good gives lerp_amt of 1, very bad gives 0
lerp_amt = min(max((2*DAILY_STD_DEV + pct_change)/(4*DAILY_STD_DEV), 0), 1)
lerped_hue = int(lerp_amt*GOOD_HUE + (1-lerp_amt)*BAD_HUE)
lerped_color = [int(255*x + 0.5) for x in colorsys.hsv_to_rgb(lerped_hue/360.0,1.0,1.0)]
highlight_color = [int((255+i)/2) for i in lerped_color]

#Main color
my_color = "#" + ''.join([hex(i)[2:].zfill(2) for i in lerped_color])
#Color for breathe effect ... brighter version of main color
emph_color = "#" + ''.join([hex(i)[2:].zfill(2) for i in highlight_color])

if(verbose):
    print "my_color: " + my_color
    print "emph_color: " + emph_color

###########################
#First, set the light color

#Build the payload
payload = {
    'power'    : 'on',
    'color'    : my_color,
    'duration' : 5,
}

#Send it, and check results
response = requests.put("https://api.lifx.com/v1/lights/" + SELECTOR + "/state", params=payload, headers=headers)
response.raise_for_status()

###########################
#If it is a big change, do the breathe effect
if abs(pct_change) > 2*DAILY_STD_DEV:
    #The bigger the change, the faster the breathe effect. But keep it
    # between 1 and 8 cycles per second
    breathe_rate = min(max(abs(2/(pct_change/DAILY_STD_DEV)), 1), 8)

    #Build the payload
    payload = {
        'power_on'   : 'true', #Light should already be on, but just in case.
        'from_color' : my_color,
        'color'      : emph_color,
        'period'     : breathe_rate,
        'cycles'     : (1/breathe_rate)*CALL_FREQUENCY*60, #Repeat until the next script call
        'persist'    : 'true'
    }

    #Send message and check response
    response = requests.post("https://api.lifx.com/v1/lights/" + SELECTOR + "/effects/breathe", params=payload, headers=headers)
    response.raise_for_status()
