from base_gpio_interface import BaseGPIOInterface

import RPi.GPIO as GPIO # pylint: disable=import-error


class RPiGPIOInterface(BaseGPIOInterface):

    def setup_gpio(self, pull_str=None, trigger_str=None, _=None):
        if not GPIO:
            self.logger.warning("No RPi.GPIO module - disabling GPIO interface")
            return False
        else:
            GPIO.setmode(GPIO.BOARD)
            GPIO.setwarnings(False)
            if pull_str == "up":
                self.pull = GPIO.PUD_UP
            elif pull_str == "down":
                self.pull = GPIO.PUD_DOWN
            else:
                self.pull = None
            # string only trigger, we are not using RPi.GPIO triggers in this implementation, 
            if trigger_str not in ("rising", "falling", "both"):
                self.logger.warning("Error starting RPi.GPIO: unknown trigger type in config. Should be one of rising, falling, both")
                self.trigger = "both"
            else:
                self.trigger = trigger_str
            return True
            # trigger setup using RPi.GPIO  
            # if trigger_str == "rising":
            #     self.trigger = GPIO.RISING
            # elif trigger_str == "falling":
            #     self.trigger = GPIO.FALLING
            # elif trigger_str == "both":
            #     self.trigger = GPIO.BOTH
            # else:
            #     self.logger.warning("Error starting RPi.GPIO: unknown trigger type in config. Should be one of rising, falling, both")
            #     self.trigger = None

    def setup_input(self, pin_number, pull=None):
        try:
            if pull:
                GPIO.setup(pin_number, GPIO.IN, pull_up_down=pull)
            else: #TODO recheck pull_up_down=None here, should it be so when pull_str is "down"?
                GPIO.setup(pin_number, GPIO.IN)
        except RuntimeError:
            try:
                GPIO.cleanup()
            except RuntimeError:
                self.logger.error("Exception during GPIO pins setup:")
                self.enabled = False
        else:
            return pin_number

    def read_level(self, pin_number):
        return GPIO.input(pin_number)

    def close(self):
        self.enabled = False
        if GPIO:
            GPIO.cleanup()
