#!/usr/bin/env python3

import json
import os

SERIAL_DIRECTORY = "/dev/serial/by-id/"

class BaseCommand(object):
    def execute(self, gcon, data):
        return {"error" : "Not yet implemented"}

class CommandListSerial(BaseCommand):
    def execute(self, gcon, data):

        if os.path.exists(SERIAL_DIRECTORY):
            serialdevices = os.listdir(SERIAL_DIRECTORY)
            serialdevices = [SERIAL_DIRECTORY + a for a in serialdevices]
        else:
            serialdevices = []

        return {"device" : serialdevices}

class CommandConnectSerial(BaseCommand):
    def execute(self, gcon, data):
        serialdevice = data["device"]

        if gcon.serialrunner.isConnected():
            return {"result": "FAILED", "reason": "serial port connection already established"}

        if not os.path.exists(serialdevice):
            return {"result" : "FAILED", "reason" : "serial port path does not exist"}


        if not gcon.serialrunner.connect(serialdevice):
            return {"result" : "FAILED", "reason" : "serial connection failed because of unknown reason. See log files for more information"}

        return {"result" : "SUCCESS"}


class CommandRequestStatus(BaseCommand):
    def execute(self, gcon, data):
        if not gcon.serialrunner.isConnected():
            return {"status" : "NOT_CONNECTED"}

        if gcon.serialrunner.isHalted():
            return {"status" : "HALTED"}

        if gcon.serialrunner.isConnected() and len(gcon.serialrunner.queue) == 0: # TODO: No File Print Running
            return {"status" : "IDLE"}

        return {"status" : "UNKNOWN"}

        # TODO: File Printing

class CommandRunGcode(BaseCommand):
    def execute(self, gcon, data):
        gcon.serialrunner.forceAddLine(data["gcode"])
        return {}


class CommandRunGcodeResult(BaseCommand):
    def execute(self, gcon, data):
        
response = gcon.serialrunner.sendline(data["gcode"])
        return {"result" : response}