######################################################################
Ansicht des Dozenten inkl. der Steuerung des Dashboards und der Lampen
######################################################################

# Bibliotheken einbinden
import RPi.GPIO as GPIO
import time
import math
import gspread
from oauth2client.service_account import ServiceAccountCredentials
import requests

# Link zum GoogleSheet https://docs.google.com/spreadsheets/d/11N64tz0XctBRAJk4C9Pd4yC_J9pENiLCzZknrnzW1Hg/edit#gid=0

# Webhooks
data = 'https://maker.ifttt.com/trigger/dozent_clear/with/key/bhN1Omd1FWPjHsC3_akFzq'
#Zweiter Webhook

# Autorisierung der Google Drive API
scope = [
    'https://www.googleapis.com/auth/drive',
    'https://www.googleapis.com/auth/drive.file'
]
file_name = 'iothackathon-423543aa9b7f.json'
creds = ServiceAccountCredentials.from_json_keyfile_name(file_name, scope)
client = gspread.authorize(creds)


# GPIO Modus (BOARD / BCM)
GPIO.setmode(GPIO.BCM)

# GPIO Pins zuweisen
GPIO_TRIGGER = 23
GPIO_ECHO = 24

OLD_STATUS = 0
DISTANCE_THRESHOLD = 80

# Richtung der GPIO-Pins festlegen (IN / OUT)
GPIO.setup(GPIO_TRIGGER, GPIO.OUT)
GPIO.setup(GPIO_ECHO, GPIO.IN)

# Messung der Distanz zur Ermittlung ob der Dozent vor dem Dashboard sitzt.
def distanz():
    # setze Trigger nach 0.01ms auf LOW
    GPIO.output(GPIO_TRIGGER, True)
    time.sleep(0.00001)
    GPIO.output(GPIO_TRIGGER, False)

    StartZeit = time.time()
    StopZeit = time.time()

    # speichere Startzeit
    while GPIO.input(GPIO_ECHO) == 0:
        StartZeit = time.time()

    # speichere Ankunftszeit
    while GPIO.input(GPIO_ECHO) == 1:
        StopZeit = time.time()

    # Zeit Differenz zwischen Start und Ankunft
    TimeElapsed = StopZeit - StartZeit
    # mit der Schallgeschwindigkeit (34300 cm/s) multiplizieren
    # und durch 2 teilen, da hin und zurueck
    distanz_n = (TimeElapsed * 34300) / 2

    return distanz_n

# Methode zur Erkennung und zum Loesen der gelesenen Eintraege im Google Sheet
def mark_as_seen():
    list_of_cells = []
    sheet = client.open('Fragenuebersicht').sheet1
    list_of_cells = sheet.findall('Ungelesen')
    len(list_of_cells)
    for cell in list_of_cells:
        cell.value = 'Gelesen'
    sheet.update_cells(list_of_cells)

# Main Methode, die bis zum Abbruch dauerhaft ausgefuehrt wird
if __name__ == '__main__':
    try:
        while True:
            neueDistanz = distanz()
            #mark_as_seen()
            #time.sleep(500)
            if math.fabs((neueDistanz-OLD_STATUS))>=DISTANCE_THRESHOLD:
                OLD_STATUS = neueDistanz
                if neueDistanz >= 50:
                    iso_time = time.strftime("%Y-%m-%d-T%H:%M:%S")
                else:
                    iso_time = time.strftime("%Y-%m-%d-T%H:%M:%S")
                    print("Dozent erkannt")
                    webhook_dozent = requests.post(data)
                    try:
                        mark_as_seen()
                    except:
                        time.sleep(2)
                    time.sleep(20)

# Beim Abbruch durch STRG+C resetten
    except KeyboardInterrupt:
        print("Messung vom User gestoppt")
        GPIO.cleanup()