"""
Name: onionIO
Title: 
Author: Cooper
Date: 10/01/2019

Desc: Class to handle the Linux sysfs stuff.  Not sure what I am doing here...

"""
import logging
logger = logging.getLogger("onionIO")

class OnionIO(object):
    def __init__(self, ioPin):
        self.ioPin = ioPin

        self.ioTopDir = "/sys/class/gpio"
        self.ioExpDir = "/sys/class/gpio/export"
        self.ioUnExpDir = "/sys/class/gpio/unexport"
        self.ioDir = "/sys/class/gpio/gpio%d" % self.ioPin

    def initialiseIO(self):
        try:
            exf = open(self.ioExpDir, "w")
            exf.write("%s" % self.ioPin)
        except IOError as e:
            logging.exception(e)
            return -1

        return 0

    def clearIO(self):
        try:
            exf = open(self.ioUnExpDir, "w")
            exf.write("%s" % self.ioPin)
        except IOError:
            return -1

        return 0

    def setDirection(self, dir):
        status = self.initialiseIO()

        if status == 0:
            if dir == 0 or dir == 1:
                try:
                    iofilepath = self.ioDir + "/direction"
                    iofile = open(iofilepath, "w")
                    iofile.write("%s" % dir)

                    logging.info("IO: Setup OK!")
                    return 0
                except FileNotFoundError:
                    return -1
            else:
                logging.info("IO: Invalid direction")
                return -1

        else:
            logging.info("IO: Cannot set direction")
            return -1


    def getIOValue(self):
        status = self.initialiseIO()

        if status == 0:
            iofilepath = self.ioDir + "/value"
            try:
                iofile = open(iofilepath, "r")
                state = iofile.read()

                self.clearIO()
            except FileNotFoundError:
                state = 1

            return state
        else:
            return "-1"

    def setIOValue(self, value):
        pass


if __name__ == "__main__":
    import time

    oio = OnionIO(29)
    oio.setDirection(0)

    while 1:
        print(oio.getIOValue())
        time.sleep(1)
