from time import sleep
import gpiozero as GP
from signal import pause

import base64
import sys
from Cryptodome.PublicKey import RSA
from Cryptodome.Cipher import PKCS1_OAEP

import urllib2

import traceback

if len(sys.argv) < 2:
    print "No id"
    exit(1)

if len(sys.argv) < 3:
    print "No url"
    exit(1)

ext = ""
if len(sys.argv) > 3:
    ext = sys.argv[3]

id = int(sys.argv[1])
url_base = sys.argv[2]

l = GP.LED(18)

b = GP.Button(16)

l.source = b

status = False

private_key = RSA.import_key(open("private.pem").read())
rsa = PKCS1_OAEP.new(private_key);

while True:
    now_pressed = b.is_pressed
    if now_pressed == status:
        if now_pressed:
            b.wait_for_release(5)
        else:
            b.wait_for_press(5)
        now_pressed = b.is_pressed
    if now_pressed != status:
        status = now_pressed

        print "status now: " + str(status)

        try:
            response = urllib2.urlopen(baseUrl + "/status-update" + ext + ".php?door_id=" + str(id) + "&status=" + ("1" if status else "0"))

            enc_verify = base64.b64decode(response.read())

            verify = rsa.decrypt(enc_verify)

            print " verifying with: " + verify

            response = urllib2.urlopen(baseUrl + "/verify-status" + ext + ".php?door_id=" + str(id) + "&verify=" + verify)
            print " returned: " + response.read()
        except Exception as e:
            print str(e)
            traceback.print_tb(sys.exc_info()[2])

        sleep(1)
