 #!/usr/bin/python

import sys 
import tty 
import termios 
import time 
import thread 
import os
import signal
import pylcdlib

import RPi.GPIO as GPIO 
import logging 
import db 
import MFRC522 
import MySQLdb




# Nastavi na hodnotu True pre pouzitie ladenia.
DEBUG = True 
if(DEBUG):
    logging.basicConfig(format='%(asctime)s %(message)s',filename='/var/log/syslog',datefmt='%d/%m/%Y %I:%M:%S %p',level=logging.DEBUG)


# Prepojenie s databazou
def connect():
    # Nastavenie pripojenia k Mysql a zadanie potrebnych udajov
    return MySQLdb.connect(host="localhost", user="kolejni", passwd="admin", db="brno")

# Start
class Actions:
    incomming=1
    outcomming=2





# Pripravenie RFID na citanie
def identity():
    reading = True
    while reading:
        MIFAREReader = MFRC522.MFRC522()
        (status,TagType) = MIFAREReader.MFRC522_Request(MIFAREReader.PICC_REQIDL)
        if status == MIFAREReader.MI_OK:
            print("Karta detekovana. Identifikacia...")
        (status,backData) = MIFAREReader.MFRC522_Anticoll()
        if status == MIFAREReader.MI_OK:
            print ("ID Karty: "+str(backData[0])+""+str(backData[1])+""+str(backData[2])+""+str(backData[3])+""+str(backData[4]))
            MIFAREReader.AntennaOff()
            reading=False
            return str(backData[0])+str(backData[1])+str(backData[2])+str(backData[3])+str(backData[4]) 
def setGpio():
	# Zobrazenie bez varovania
    GPIO.setwarnings(False)
    # Pouzitie GPIO pinov
    GPIO.setmode(GPIO.BOARD)





# Vybrat ID karty
def read():
    cardId=identity()
    return cardId
     
def readNfc(action):

    # Moznost 1: Prichod
    if(action==49):
        print("Prichod domov:")
        print("Prilozte kartu!")
        #lcd.lcd_puts("nazdar",1)
        bashCommand = "sudo python /home/pi/test_lcd4.py"
        os.system(bashCommand)
        cardId=read()
        # Skontroluje ci je karta v databaze
        db2 = connect()
        c = db2.cursor()
        check = c.execute("SELECT *FROM cards WHERE tagId = " + cardId)
        time.sleep(1);
        
        # Ak je karta v databaze schvali a povoli vstup
        if check:
            name = db.write(cardId,Actions.incomming)
			bashCommand = "sudo python /var/www/odblokovanie.sh"
            os.system(bashCommand)
            print "Mozte vstupit!"
            bashCommand = "sudo python /home/pi/test_lcd5.py"
            os.system(bashCommand)
			
        else:
            print "Nemate povolenie na vstup!"
            bashCommand = "sudo python /home/pi/test_lcd6.py"
            os.system(bashCommand)
        logging.info("%s - Arrive",cardId)

    # Option 2 - Odchod
    if(action==50):
        print("Odchod z domu:")
        print("Prilozte kartu!")
        bashCommand = "sudo python /home/pi/test_lcd7.py"
        os.system(bashCommand)
        cardId=read()
        # Check if card ID is in db
        db2 = connect()
        c = db2.cursor()
        check = c.execute("SELECT *FROM cards WHERE tagId = " + cardId)
        time.sleep(1);
        # If card ID isin db approve and authorize leave
        if check:
            name = db.write(cardId,Actions.outcomming)
			bashCommand = "sudo python /var/www/zakodovanie.sh"
            os.system(bashCommand)
            print "Zabezpecenie bolo spustene."
            bashCommand = "sudo python /home/pi/test_lcd8.py"
            os.system(bashCommand)
        else:
            print "Zabezpecenie sa nespustilo nespravna karta!"
            bashCommand = "sudo python /home/pi/test_lcd9.py"
            os.system(bashCommand)
        logging.info("%s - Leaving",cardId)


    # Option 3 - Add new card user
    if(action==51):
        print("Zadaj meno:")
        userId = raw_input('--> ')
        bashCommand = "sudo python /home/pi/test_lcd10.py"
        os.system(bashCommand)
        print("Uroven opravnenia (1:Uzivatel | 2:Host)?")
        permission = raw_input('-->')
        bashCommand = "sudo python /home/pi/test_lcd11.py"
        os.system(bashCommand)
        print("Prilozte kartu!")
        bashCommand = "sudo python /home/pi/test_lcd12.py"
        os.system(bashCommand)  
        cardId=read()
        name = db.writeUser(userId,cardId,permission)
        print(name)
        logging.info("Vytvorenie novej karty uzivatela: %s, Permission: %s",userId,permission) 
fd = sys.stdin.fileno() 
old = termios.tcgetattr(fd) 
def getOneKey():
    try:
        tty.setcbreak(sys.stdin.fileno())
        ch = sys.stdin.read(1)
        return ord(ch)
    finally:
        termios.tcsetattr(fd, termios.TCSADRAIN, old) 

def main():



    try:
        setGpio()
        while True:

            print("=============================================")
            print("Vitajte.")
            print("Zadajte vasu poziadavku:")
            print("[1]Prichod - odblokovanie")
            print("[2]Odchod  - zablokovanie")
            print("[3]Pridanie noveho uzivatela")
            print("=============================================")
    
            bashCommand = "sudo python /home/pi/test_lcd3.py"
            os.system(bashCommand) 

            choice = getOneKey()
            readNfc(choice)

    except KeyboardInterrupt:
        GPIO.cleanup()
        pass
    GPIO.cleanup() 

if __name__ == '__main__':
    main()
