#!/usr/bin/env python3

import shepherd.config
import shepherd.module

import sys
import os
import time
import argparse

from gpiozero import OutputDevice, Device
from gpiozero.pins.pigpio import PiGPIOFactory

from shepherd.modules.betterservo import BetterServo

Device.pin_factory = PiGPIOFactory()


APHIDTRAP_LED_PIN = 5 #Out2


class AphidtrapConfDef(shepherd.config.ConfDefinition):
    def __init__(self):
        super().__init__()


class AphidtrapModule(shepherd.module.SimpleModule):
    conf_def = AphidtrapConfDef()

    def setup(self):

        print("Aphidtrap config:")
        print(self.config)

        self.led_power = OutputDevice(APHIDTRAP_LED_PIN,
                                   active_high=True,
                                   initial_value=False)

    def setup_other_modules(self):
        self.modules.picam.hook_pre_cam.attach(self.led_on)
        self.modules.picam.hook_post_cam.attach(self.led_off)

    def led_on(self):
        self.led_power.on()

    def led_off(self):
        self.led_power.off()



def main(argv):
    argparser = argparse.ArgumentParser(
      description='Module for aphidtrap control functions. Run for testing')
    argparser.add_argument("configfile", nargs='?', metavar="configfile",
                           help="Path to configfile", default="conf.toml")


    args = argparser.parse_args()
    confman = shepherd.config.ConfigManager()

    srcdict = {"aphidtrap": {}}

    if os.path.isfile(args.configfile):
        confman.load(args.configfile)
    else:
        confman.load(srcdict)

    aphidtrap_mod = AphidtrapModule(confman.get_config("aphidtrap", AphidtrapConfDef()),
                                  shepherd.module.Interface(None))
                                  
    aphidtrap_mod.led_on()
    time.sleep(2)
    aphidtrap_mod.led_off()


if __name__ == "__main__":
    main(sys.argv[1:])
