#!/usr/bin/env python3

from serial import Serial
from serial.tools.list_ports import comports as port_list

from remotes import tv, movie_box

from pprint import pprint
from time import sleep

ser = Serial(timeout=1)
ser.baudrate = 9600
#ser.port = '/dev/ttyACM0'

# Find the first Arduino we can find (Or verify the port we got is valid)
ports_open = port_list(False)
found = False
for p in ports_open:
    print("Device: /dev/{0:8}  Manufacturer: {1}".format(p.name, p.manufacturer))
    if ser.port == None:
        if p.manufacturer == "Arduino (www.arduino.cc)":
            found = True
            ser.port = "/dev/{0}".format(p.name)
            print("Automagically found an Arduino on port '/dev/{0}'!".format(p.name))
            break # Stop needlessly looping over devices
    else:
        if '/dev/{0}'.format(p.name) == ser.port:
            found = True
            print("Found your Arduino!")
            break # Stop needlessly looping over devices

# Verify I have found a Arduino
if not found:
    raise TypeError("Device '{0}' not found!".format(ser.port))

# Attempts to send the requested code
def send_code(ky, target):
    if target == "tv":
        if ky in tv:
            msg = "0x{0},{1},1\n".format(tv[ky], tv["_config"]["size"])
            ser.write(msg.encode())
            #print("< Sent {0} {1}".format(ky, msg.encode()))
            print("< Sent {0}".format(ky))
        else:
            print("Invalid key")
    elif target == "mb":
        if ky in movie_box:
            msg = "0x{0},{1},0\n".format(movie_box[ky], movie_box["_config"]["size"])
            ser.write(msg.encode())
            #print("< Sent {0} {1}".format(ky, msg.encode()))
            print("< Sent {0}".format(ky))
        else:
            print("Invalid key")
# Ok we are ready to actually open the Serial port
ser.open()
print("Opened!")
#while ser.is_open: # While the connection is open
#    line = ser.readline().decode().strip("\n").strip("\r") # Attempt to read a line
#    if line != "": # If there is a line Pretty Print it to the screen
#        print("> {0}".format(line))
