from django.core.context_processors import csrf
from django.template import RequestContext, Context, loader
from django.shortcuts import render_to_response

from PyMPUSBAPI import USBApi

api = USBApi()

def index(request):

    print request.POST
    dict = request.POST

    if 'action' in dict:
        print 'Action = ' + dict['action']
        if dict['action'] == 'start':
            seconds_to_count = int(dict['sec']) + 60 * int(dict['min'])
            dips = int(dict['dips'])
            sugar = int(dict['sugar'])
            data =  [4, seconds_to_count/255, seconds_to_count%255, dips, sugar]
            print data
            api.easy_command(data, 1)#Stop
        else: 
            api.easy_command([3], 1)#Stop  

    #Get Status of DeBagger hardware
    rx_data = api.easy_command([0], 11)
    print rx_data
    
    #rx_data = (1, [0, 4, 0, 0, 90, 0 ,20, 2, 0, 1, 0]) #For testing purposes only
    
    if rx_data[0] == 0:
        hw_state = {
        'device_missing': 1 }
        
    else:
        hw_state = {
        'state' : rx_data[1][1],
        'time' : rx_data[1][3]*255 + rx_data[1][4],
        'elapsed_time' : rx_data[1][5]*255+ rx_data[1][6],
        'num_of_dips' : rx_data[1][7],
        'dip_counter' : rx_data[1][8],
        'num_of_sugar' : rx_data[1][9],
        'sugar_counter' : rx_data[1][10]}
        
        hw_state['ready'] = hw_state['state']==0
        hw_state['steeping'] = hw_state['state']==4 or hw_state['state']==1
        hw_state['dipping'] = hw_state['state']==3
        hw_state['disposing'] = hw_state['state']==5 or hw_state['state']==6 or hw_state['state']==2
        hw_state['remaining_min'] = (hw_state['time'] - hw_state['elapsed_time'])/60
        hw_state['remaining_sec'] = (hw_state['time'] - hw_state['elapsed_time'])%60
        
        hw_state['min_select'] = create_html_selection(10, hw_state['time']/60)
        hw_state['sec_select'] = create_html_selection(60, hw_state['time']%60, 10)
        hw_state['dips_select'] = create_html_selection(5, hw_state['num_of_dips'])
        hw_state['sugar_select'] = create_html_selection(3, hw_state['num_of_sugar']) 
    
    hw_state.update(csrf(request))   
    
    #print hw_state
    return render_to_response('index.html', hw_state)

    
def create_html_selection(range_val, selected_value, step = 1):
    html_code = ''  
    for x in range(0, range_val, step):
        if x == selected_value:
            selected = ' SELECTED'
        else:
            selected = ''                                                      
        html_code = html_code + '<option value="'+str(x)+'"'+selected+'>'+str(x)+'</option>\n'
    return html_code