import commands
import requests
import json
from time import sleep
from datetime import datetime
from threading import Timer

import Adafruit_CharLCD as LCD
import Adafruit_BBIO.GPIO as GPIO


printers = [["10.140.68.158" ,"RCVUKA", "004250150197"], 
            ["10.140.68.184" ,"zartan", "004204150007"],
            ["10.140.68.76"  ,"Scarlet", "004204150033"],
            ["10.140.68.152" ,"Far Left", "004204130007"],
            ["10.140.68.174" ,"Bionic", "004204150036"],
            ["10.140.68.189" ,"9308", "004250140005"],
            ["10.140.68.84"  ,"Theodore Armand-Ribot", "004250140014"],
            ["10.140.68.80"  ,"toothy", "004213150081"]]

printerIndex = 1

#button configuration:
leftButton   = 'P8_15'
rightButton  = 'P8_17'
bottomButton = 'P9_25'
topButton    = 'P9_23'

buttonPressed = False

GPIO.setup(leftButton, GPIO.IN)
GPIO.setup(rightButton, GPIO.IN)
GPIO.setup(bottomButton, GPIO.IN)
GPIO.setup(topButton, GPIO.IN)

# LCD configuration:
lcd_rs = 'P8_8'
lcd_en = 'P8_10'
lcd_d4 = 'P8_18'
lcd_d5 = 'P8_16'
lcd_d6 = 'P8_14'
lcd_d7 = 'P8_12'
lcd_red   = 'P9_16'
lcd_green = 'P9_14'
lcd_blue  = 'P8_13'

# Define LCD column and row size for 16x2 LCD.
lcd_columns = 16
lcd_rows    = 2

# make sure the embers have all the same addresses at 1AM everyday
# see https://stackoverflow.com/questions/15088037/python-script-to-do-something-at-the-same-time-every-day
x=datetime.today()
y=x.replace(day=x.day+1, hour=1, minute=0, second=0, microsecond=0)
delta_t=y-x

secs=delta_t.seconds+1


def findEmbers():
    global printers
    for i in xrange(0,255):
        try:
            params = {"command":"getboardnum"}
            try:
                requests.get('http://10.140.68.%d/command' % i, timeout=1)
                r = requests.post('http://10.140.68.%d/command' % i, params)
                try:
                    decoded = json.loads(r.text.lower())['response']
                    print decoded
                    #find the index of the printer with this board number
                    foundPrinter = [j for j, v in enumerate(printers) if v[2] == decoded]
                    #check that it's one that we're expecting
                    if foundPrinter:
                        printers[foundPrinter[0]][0] = '10.140.68.%d' % i
                except ValueError:
                    # print 'JSON errrrrr'
                    pass
            except requests.exceptions.Timeout:
                # print 'timout on 10.140.68.%d' % i
                pass
        except requests.exceptions.ConnectionError:
            # print 'error on 10.140.68.%d' % i
            pass

t = Timer(secs, findEmbers())
t.start()

# Initialize the LCD using the pins
lcd = LCD.Adafruit_RGBCharLCD(lcd_rs, lcd_en, lcd_d4, lcd_d5, lcd_d6, lcd_d7,
                              lcd_columns, lcd_rows, lcd_red, lcd_green, lcd_blue)
lcd.set_color(1.0,1.0,1.0)


def getBoardNo():
    params = {"command":"getboardnum"}
    try:
        r = requests.post("http://" + printers[printerIndex][0] + '/command', params)
        decoded = json.loads(r.text.lower())['response']
        return decoded
    except requests.exceptions.ConnectionError:
        pass


def displayPrinterName():
    lcd.clear()
    lcd.message(printers[printerIndex][1] + '\n' + printers[printerIndex][0])


def advancePrinterIndex():
    global printerIndex
    printerIndex += 1
    if printerIndex > len(printers)-1:
        printerIndex = 0
    return


def decreasePrinterIndex():
    global printerIndex
    printerIndex -= 1
    if printerIndex < 0:
        printerIndex = len(printers)-1
    return


def sendButton1():
    #double check we have the right Ember
    if getBoardNo() != printers[printerIndex][2]:
        lcd.clear()
        lcd.message("Printer not at IP")
        return
    command = 'ssh -q -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null root@' + printers[printerIndex][0] + ' \'echo button1 > /tmp/CommandPipe\''
    commands.getstatusoutput(command)
    return


def sendButton2():
    #double check we have the right Ember
    if getBoardNo() != printers[printerIndex][2]:
        lcd.clear()
        lcd.message("Printer not at IP")
        return
    command = 'ssh -q -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null root@' + printers[printerIndex][0] + ' \'echo button2 > /tmp/CommandPipe\''
    commands.getstatusoutput(command)
    return


displayPrinterName()
while True:
    if not buttonPressed:
        if GPIO.input(topButton):
            advancePrinterIndex()
            displayPrinterName()
            sleep(0.2)
            buttonPressed = True
        elif GPIO.input(bottomButton):
            decreasePrinterIndex()
            displayPrinterName()
            sleep(0.2)
            buttonPressed = True
        elif GPIO.input(leftButton):
            sendButton2()
            sleep(0.2)
            buttonPressed = True
        elif GPIO.input(rightButton):
            sendButton1()
            sleep(0.2)
            buttonPressed = True
    else:
        buttonPressed = False
    sleep(0.1)
