#!/usr/bin/python

# this script is started in /etc/rc.local using this command:
# python /home/osmc/.kodi/userdata/switch.py &

# when OSCM is running, it stats autoexec.py which reads the text file with which channel should be playing

# remember to install GPIO for python:
# see https://discourse.osmc.tv/t/gpio-control-need-some-help/3246/3 for more

import RPi.GPIO as GPIO
import time
import subprocess
from subprocess import call

GPIO.setmode(GPIO.BOARD)

GPIO.setup(5, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(7, GPIO.IN, pull_up_down=GPIO.PUD_UP)

selected = 99


def saveChanges( knop ):
    global selected
    if knop != selected: # only write to the file if something has changed
        kn = open('/home/osmc/.kodi/temp/knop.txt', 'w')
        kn.write( str(knop) )
        print( str(knop) )
        kn.close()
        selected = knop
        time.sleep(0.2) # debounce
    return



# poll pins
while True:

    # let's assume no pin is connected
    found = False

    if GPIO.input(5) == False:
        saveChanges('0') # if the plug is put in the socket, then save this state to the text file
        found = True

    if GPIO.input(7) == False:
        # if the shutdown button is pushed, then stop everything and shutdown the system
        # first turn the monitor back on, otherwise shutting down will not go smoothly for some reason
        subprocess.call( "/opt/vc/bin/tvservice --explicit='DMT 35 HDMI'; fbset -depth 8; fbset -g 1280 1024 1280 1024 16;", shell=True )
        call("sudo nohup shutdown -h now", shell=True) 
        break

    # if no pin is selected (which means the plug is disconnected from the socket), then reset to a default
    if found == False:
        saveChanges(99)
	
    time.sleep(0.2)
