import serial
import time
import sys

# Serial configurations
SERIAL_PORT = '/dev/ttyUSB0'
BAUD_RATE = 19200

USAGE_INFO = "Usage: python3 smarttv.py [power_on|power_off|get_state|get_volume|set_volume=volume|get_mute|mute|unmute|get_input|set_input_hdmi|set_input_ops]"

USAGE_INF = """
Usage: python3 smarttv.py [command]

Commands:
  power_on            - Turn the smart TV on
  power_off           - Turn the smart TV off
  get_state           - Get the power state of the smart TV
  get_volume          - Get the current volume level of the smart TV
  set_volume=volume   - Set the volume level of the smart TV (0-100)
  get_mute            - Check if the smart TV is muted
  mute                - Mute the smart TV
  unmute              - Unmute the smart TV
  get_input           - Get the current input source of the smart TV
  set_input_hdmi      - Set the input source to HDMI
  set_input_ops       - Set the input source to OPS/HDMI2
  help                - Display help information
"""

# Define commands
SMARTTV_HELP = b'?\r'
SMARTTV_ON = b'on\r'
SMARTTV_OFF = b'off\r'
SMARTTV_GET_MUTE = b'get mute\r'
SMARTTV_MUTE = b'set mute=on\r'
SMARTTV_UNMUTE = b'set mute=off\r'
SMARTTV_GET_STATE = b'get powerstate\r'
SMARTTV_GET_VOLUME = b'get volume\r'
SMARTTV_SET_VOLUME = b'set volume=%d\r'
SMARTTV_GET_POWERSTATE = b'get powerstate\r'
SMARTTV_GET_INPUT = b'get input\r'
SMARTTV_SET_INPUT_HDMI = b'set input=hdmi1\r'
SMARTTV_SET_INPUT_OPS= b'set input=ops/hdmi2\r'

## MQTT
MQTT_IP = "locahost"
MQTT_PORT = 1883
MQTT_USERNAME = "username"
MQTT_PASSWORD = "password"
MQTT_TOPIC_CMD = "smarttv/cmd"
MQTT_TOPIC_STATUS = "smarttv/status"

# Function to send command to TV
def send_command(command):
    with serial.Serial(SERIAL_PORT, BAUD_RATE, timeout=1) as ser:
        ser.write(command)
        time.sleep(0.1)  # Wait for command to be sent
        reply = ser.read(100)  # Read up to 100 bytes of reply
        return reply.decode('utf-8')  # Decode bytes to string

if __name__ == "__main__":
    if len(sys.argv) != 2:
        print(USAGE_INFO)
        sys.exit(1)

    command = sys.argv[1]
    if "=" in command:
        command_parts = command.split("=")
        if len(command_parts) != 2 or command_parts[0] != "set_volume":
            print("Usage: python3 smarttv.py set_volume=volume")
            sys.exit(1)
        volume = int(command_parts[1])
        if not 0 <= volume <= 100:
            print("Volume must be between 0 and 100")
            sys.exit(1)
        volume_command = SMARTTV_SET_VOLUME % volume
        response = send_command(volume_command)
        if "olume=" in response:
            volume_level = response.split('=')[1].rstrip('>').strip()
            print('{"volume":' + volume_level + '}')
        sys.exit(0)

    if command == "help":
        print(send_command(SMARTTV_HELP))

    elif command == "power_on":
        response = send_command(SMARTTV_ON)
        if "owerstate=on" in response:
            print('{"power_state":"on"}')
        else:
            print(send_command(SMARTTV_ON))

    elif command == "power_off":
        response = send_command(SMARTTV_OFF)
        if "owerstate=off" in response:
            print('{"power_state":"off"}')
        elif "powerstate=standby" in response:
            print('{"power_state":"off"}')
        else:
            print(send_command(SMARTTV_OFF))

    elif command == "get_state":
        print(send_command(SMARTTV_GET_STATE))

    elif command == "get_volume":
        response = send_command(SMARTTV_GET_VOLUME)
        if "olume=" in response:
            volume_level = response.split('=')[1].rstrip('>').strip()
            print('{"volume":' + volume_level + '}')
        else:
            print(response)

    elif command == "get_mute":
        response = send_command(SMARTTV_GET_MUTE)
        if "ute=off" in response:
            print('{"mute":"off"}')
        elif "ute=on" in response:
            print('{"mute":"on"}')
        else:
            print(response)

    elif command == "mute":
        response = send_command(SMARTTV_MUTE)
        if "ute=off" in response:
            print('{"mute":"off"}')
        elif "ute=on" in response:
            print('{"mute":"on"}')
        else:
            print(response)
        
    elif command == "unmute":
        response = send_command(SMARTTV_UNMUTE)
        if "ute=off" in response:
            print('{"mute":"off"}')
        elif "ute=on" in response:
            print('{"mute":"on"}')
        else:
            print(response)

    elif command == "get_powerstate":
        response = send_command(SMARTTV_GET_POWERSTATE)
        if "owerstate=on" in response:
            print('{"power_state":"on"}')
        elif "owerstate=off" in response:
            print('{"power_state":"off"}')
        elif "owerstate=standby" in response:
            print('{"power_state":"off"}')
        else:
            print(response)
  
    elif command == "get_input":
        response = send_command(SMARTTV_GET_INPUT)
        if "nput=ops/hdmi2" in response:
            print("OPS")
        elif "nput=hdmi1" in response:
            print('{"input":"HDMI"}')
        else:
            print(send_command(SMARTTV_GET_INPUT))
            
    elif command == "set_input_hdmi":
        response = send_command(SMARTTV_SET_INPUT_HDMI)
        if "nput=hdmi1" in response:
            print("HDMI")
        else:
            print(send_command(SMARTTV_SET_INPUT_HDMI))
       
    elif command == "set_input_ops":
        response = send_command(SMARTTV_SET_INPUT_OPS)
        if "nput=ops/hdmi2" in response:
            print("OPS")
        else:
            print(send_command(SMARTTV_SET_INPUT_OPS))

    else:
        print("Invalid command.", USAGE_INFO)
        sys.exit(1)