#!/usr/bin/python3
import RPi.GPIO as GPIO
import statemachine, actor, pins, tysock, waker, spaceapi
from libtuer import logger
import argparse

# Parse arguments
parser = argparse.ArgumentParser(description='Run a door')
parser.add_argument("-d", "--debug",
					action="store_true", dest="debug",
					help="Don't send emails")
parser.add_argument("-f", "--fallback",
					action="store_true", dest="fallback",
					help="Fallback mode for unfunctional hardware: Depend on less sensor input")
args = parser.parse_args()
if args.debug:
	import libtuer
	libtuer.mailAddress = []
if args.fallback:
	logger.info("Starting in fallback mode")
else:
	# to avoid exceptions or getting None
	args.fallback = False

# Not let's go!
logger.info("Starting up...")

# initialize GPIO stuff
GPIO.setmode(GPIO.BOARD)

# bring 'em all up
the_actor = actor.Actor()
the_waker = waker.Waker()
the_api   = spaceapi.SpaceApi(the_waker)
the_machine = statemachine.StateMachine(the_actor, the_waker, the_api, args.fallback)
the_socket = tysock.TySocket(the_machine)
the_pins = pins.PinsWatcher(the_machine)

# we do the socket accept thing in the main thread
try:
	the_socket.accept()
except KeyboardInterrupt:
	# this is what we waited for!
	pass

logger.info("Terminating...") # somehow this does not arrive in the syslog

# bring 'em all down
the_waker.stop() # this one first, it "randomly" calls other threads
the_pins.stop() # as does this
the_machine.stop()
the_api.stop()
the_actor.stop()

# shutdown GPIO stuff
GPIO.cleanup()