#!/usr/bin/env python3
from flask import Flask, render_template, request
from paste.translogger import TransLogger
import RPi.GPIO as GPIO
from waitress import serve


RELAIS_1_GPIO = 17
app = Flask(__name__)


def setup():
    print('Running setup')
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(RELAIS_1_GPIO, GPIO.OUT)
    GPIO.output(RELAIS_1_GPIO, GPIO.HIGH)  # Defaulting to high/off
    print('GPIO setup, pin set to off')


@app.route('/')
def home():
    return render_template('index.html')


@app.route('/start')
def starthorn():
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(RELAIS_1_GPIO, GPIO.OUT)
    GPIO.output(RELAIS_1_GPIO, GPIO.LOW)   # Toggle switch to low/on
    return('Sending power to the relay switch, hopefully toggling a horn...')


@app.route('/stop')
def stophorn():
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(RELAIS_1_GPIO, GPIO.OUT)
    GPIO.output(RELAIS_1_GPIO, GPIO.HIGH)  # Toggle switch to high/off
    GPIO.cleanup()
    return('Ceasing power to the relay switch, hopefully silencing a horn...')


def destroy():
    return('Cleaning up GPIO')
    GPIO.cleanup()


if __name__ == '__main__':     # Program entrance
    try:
        setup()
        serve(TransLogger(app, setup_console_handler=False), listen='*:5000')
    finally:
        destroy()
