#!/usr/bin/env python3

import shepherd.config as shconf
import shepherd.plugin

import sys
import os
import time
import argparse

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

from shepherd.plugins.betterservo import BetterServo

Device.pin_factory = PiGPIOFactory()


MOTHTRAP_LED_PIN = 6
MOTHTRAP_SERVO_PIN = 10
MOTHTRAP_SERVO_POWER_PIN = 9


class MothtrapPlugin(shepherd.plugin.Plugin):
    @staticmethod
    def define_config(confdef):
        confdef.add_def('servo_open_pulse', shconf.IntDef(default=1200, minval=800, maxval=2200))
        confdef.add_def('servo_closed_pulse', shconf.IntDef(default=1800, minval=800, maxval=2200))
        confdef.add_def('servo_open_time', shconf.IntDef(default=5))

    def __init__(self, pluginInterface, config):
        super().__init__(pluginInterface, config)
        self.config = config
        self.interface = pluginInterface
        self.plugins = pluginInterface.other_plugins
        self.hooks = pluginInterface.hooks

        self.root_dir = os.path.expanduser(pluginInterface.coreconfig["root_dir"])
        self.id = pluginInterface.coreconfig["id"]

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

        servo_max = self.config["servo_open_pulse"] / 1000000
        servo_min = self.config["servo_closed_pulse"] / 1000000

        if servo_min > servo_max:
            servo_min, servo_max = servo_max, servo_min

        self.door_servo = BetterServo(MOTHTRAP_SERVO_PIN, initial_value=None,
                                      active_high=False,
                                      min_pulse_width=servo_min-0.000001,
                                      max_pulse_width=servo_max+0.000001)

        print(F"Supplied min: {servo_min}, max: {servo_max}")

        self.door_servo_power = OutputDevice(MOTHTRAP_SERVO_POWER_PIN,
                                             active_high=True,
                                             initial_value=False)

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

        self.interface.attach_hook("picam", "pre_cam", self.led_on)
        self.interface.attach_hook("picam", "post_cam", self.led_off)
        self.interface.attach_hook("picam", "post_cam", self.run_servo)

        self.interface.register_function(self.test)

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

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

    def run_servo(self):
        self.door_servo_power.on()
        time.sleep(0.5)
        
        self.door_servo.pulse_width = self.config["servo_open_pulse"] / 1000000
        time.sleep(self.config["servo_open_time"])
        
        self.door_servo.pulse_width = self.config["servo_closed_pulse"] / 1000000
        time.sleep(self.config["servo_open_time"])
        self.door_servo.detach()
        self.door_servo_power.off()

    def test(self):
        self.led_on()
        time.sleep(1)
        self.led_off()
        self.run_servo()
