import RPi.GPIO as GPIO
import time
import datetime
import os
import sys
import subprocess
from threading import Thread
from Adafruit_LED_Backpack import SevenSegment
import sqlite3

GPIO.setmode(GPIO.BCM)

GPIO.setup(5, GPIO.IN, pull_up_down = GPIO.PUD_DOWN)
GPIO.setup(6, GPIO.IN, pull_up_down = GPIO.PUD_DOWN)
GPIO.setup(13, GPIO.IN, pull_up_down = GPIO.PUD_DOWN)
GPIO.setup(19, GPIO.IN, pull_up_down = GPIO.PUD_DOWN)
GPIO.setup(26, GPIO.IN, pull_up_down = GPIO.PUD_DOWN)


GPIO.setup(17, GPIO.OUT)
GPIO.setup(27, GPIO.OUT)
GPIO.setup(22, GPIO.OUT)
GPIO.setup(14, GPIO.OUT)
GPIO.setup(15, GPIO.OUT)
GPIO.setup(18, GPIO.OUT)

GPIO.output(17, GPIO.LOW)
GPIO.output(27, GPIO.LOW)
GPIO.output(22, GPIO.LOW)
GPIO.output(14, GPIO.HIGH)
GPIO.output(15, GPIO.LOW)
GPIO.output(18, GPIO.LOW)
#GPIO.setup(26, GPIO.IN)

display = SevenSegment.SevenSegment()
display.clear()
display.begin()

global anzeige

GPIO.output(15, GPIO.HIGH)
time.sleep(0.1)
GPIO.output(18, GPIO.HIGH)
time.sleep(0.1)
GPIO.output(17, GPIO.HIGH)
time.sleep(0.1)
GPIO.output(27, GPIO.HIGH)
time.sleep(0.1)
GPIO.output(22, GPIO.HIGH)
time.sleep(0.1)

GPIO.output(15, GPIO.LOW)
time.sleep(0.1)
GPIO.output(18, GPIO.LOW)
time.sleep(0.1)
GPIO.output(17, GPIO.LOW)
time.sleep(0.1)
GPIO.output(27, GPIO.LOW)
time.sleep(0.1)
GPIO.output(22, GPIO.LOW)
time.sleep(0.1)


entprellen = datetime.datetime.now()-datetime.timedelta(microseconds = 9000000)
anzeige = True

def blinkPlayButton():
  while str(os.popen("xmms2 current -f '${playback_status}'").read()) == "Paused\n":
    GPIO.output(15, GPIO.LOW)
    time.sleep(0.5)
    GPIO.output(15, GPIO.HIGH)
    time.sleep(0.5)

def glowButton(nr, on):
  if on:
    GPIO.output(nr, GPIO.HIGH)
    time.sleep(0.5)
    GPIO.output(nr, GPIO.LOW)


def checkStatus():
  global timer
  shutCounter=0
  timer=0
  while True:
    #os.system("clear")
    timer+=1
    
    if timer < 5:
      display.clear()
      tracknr = str(os.popen("xmms2 current -f '${position}'").read())
      display.print_number_str(tracknr)
      display.write_display()
    elif timer < 10:
      playtime = str(os.popen("xmms2 current -f '${playtime}'").read())
      display.clear()
      display.set_digit(0,int(playtime[0]))
      display.set_digit(1,int(playtime[1]))
      display.set_digit(2,int(playtime[3]))
      display.set_digit(3,int(playtime[4]))
      display.set_colon(True)
      display.write_display()
    elif timer < 15:
      duration = str(os.popen("xmms2 current -f '${duration}'").read())
      display.clear()
      display.set_digit(0,int(duration[0]))
      display.set_digit(1,int(duration[1]))
      display.set_digit(2,int(duration[3]))
      display.set_digit(3,int(duration[4]))
      display.set_colon(True)
      display.write_display()
    else:
      timer=0
    #print "-> "+str(os.popen("xmms2 list | sed -n -e '1i\0' -e 's/^.*(\([0-9]*\):\([0-9]*\))$/\1 60*\2++/gp' -e '$a\60op' | dc | sed -e 's/^ *//' -e 's/ /:/g'").read())
    if str(os.popen("xmms2 current -f '${playback_status}'").read()) == "Paused\n":
      shutCounter+=1
    elif str(os.popen("xmms2 current -f '${playback_status}'").read()) == "Stopped\n":
      shutCounter+=1
    else:
      shutCounter=0
    #print "S-> "+str(shutCounter)+" "+str(timer)
    time.sleep(0.9)
    if shutCounter > 500:
      os.system("sudo halt")

def readCard(i):
    connection =sqlite3.connect("/home/pi/mapping.db")
    cursor = connection.cursor()
    while True:
        id = raw_input("warte auf Karte")
        if id == "0005302962":
          print "Eltern Modus"
          id2 = raw_input("neue Karte einlesen")
          sqlcommand="select path from jukebox where id=" + id2
          cursor.execute(sqlcommand)
          result = cursor.fetchone()
          if not result:
            print "Neue Karte"
            dirs = os.listdir("/home/pi")
            for folder in dirs:
              if "[NEU]" in folder:
                newfolder= folder.replace("[NEU]","")
                os.system('mv  "/home/pi/'+folder+'" "/home/pi/' +newfolder+'"')
                sqlcommand="insert into Jukebox VALUES("+id2+",'"+newfolder+"')"
                cursor.execute(sqlcommand)
                connection.commit()
                print folder.replace("[NEU]","")
          else:
            print "Album "+id2+" geloescht!"
            sqlcommand="delete from jukebox where id = "+id2
            cursor.execute(sqlcommand)
            connection.commit()
        else:
          sqlcommand ="select path from jukebox where id=" + id
          cursor.execute(sqlcommand)
          rows = cursor.fetchall()
          os.system("xmms2 stop")
          os.system("xmms2 clear")
          print("Lade "+rows[0][0])
          os.system("xmms2 add "+rows[0][0])
          os.system("xmms2 play")
          GPIO.output(15, GPIO.HIGH)


def toggle(i):
   os.system("xmms2 toggle")
   if str(os.popen("xmms2 current -f '${playback_status}'").read()) == "Paused\n":
      GPIO.output(15, GPIO.LOW)
      b = Thread(target=blinkPlayButton)
      b.start()
   elif str(os.popen("xmms2 current -f '${playback_status}'").read()) == "Stopped\n":
      GPIO.output(15, GPIO.LOW)
   else:
      GPIO.output(15, GPIO.HIGH)

def next(i):
   global timer
   global entprellen
   #print loslassen
   #print datetime.datetime.now()
   #print datetime.datetime.now() - loslassen
   #print datetime.timedelta(microseconds = 3000000)
   
   if datetime.datetime.now() - entprellen > datetime.timedelta(microseconds = 4000):
      time.sleep(0.3) 
      if GPIO.input(26) == 1:
         timer=5
         print "Vorspulen"
         GPIO.output(22, GPIO.HIGH)
         while GPIO.input(26) == 1:
            os.system("xmms2 seek +1")
            time.sleep(0.1)
            #timer=5
         GPIO.output(22, GPIO.LOW)
      else:
         print "Next"	
         timer=0
         os.system("xmms2 next")
         bNext = Thread(target=glowButton, args=(22,True))
         bNext.start()
      entprellen = datetime.datetime.now()
   else:
      print "zu kurz"

def prev(i):
   global timer
   global entprellen
   if datetime.datetime.now() - entprellen > datetime.timedelta(microseconds = 4000):
      time.sleep(0.3) 
      if GPIO.input(19) == 1:
         timer=5
         GPIO.output(27, GPIO.HIGH)
         print "zurueckspulen"
         while GPIO.input(19) == 1:
            os.system("xmms2 seek -1")
            time.sleep(0.1)
            #timer=5
         GPIO.output(27, GPIO.LOW)
      else:
         timer=0
         os.system("xmms2 prev")
         bPrev = Thread(target=glowButton, args=(27,True))
         bPrev.start()
         print "prev"
      entprellen = datetime.datetime.now()

def volumeUp(i):
   global entprellen
   if datetime.datetime.now() - entprellen > datetime.timedelta(microseconds = 4000):
      time.sleep(0.3)
      if GPIO.input(5) == 1:
         GPIO.output(17, GPIO.HIGH)
         while GPIO.input(5) == 1:
            os.system("xmms2 server volume +1")
            time.sleep(0.1)
         GPIO.output(17, GPIO.LOW)
      else:
         os.system("xmms2 server volume +3")
         b3 = Thread(target=glowButton, args=(17,True))
         b3.start()
      entprellen = datetime.datetime.now()

def volumeDown(i):
   global entprellen
   if datetime.datetime.now() - entprellen > datetime.timedelta(microseconds = 4000):
      time.sleep(0.3)
      if GPIO.input(6) == 1:
         GPIO.output(18, GPIO.HIGH)
         while GPIO.input(6) == 1:
            os.system("xmms2 server volume -1")
            time.sleep(0.1)
         GPIO.output(18, GPIO.LOW)
      else:
         os.system("xmms2 server volume -3")
         b3 = Thread(target=glowButton, args=(18,True))
         b3.start()
      entprellen = datetime.datetime.now()


GPIO.add_event_detect(13, GPIO.BOTH, callback = toggle, bouncetime=400)
GPIO.add_event_detect(26, GPIO.RISING, callback = next)
GPIO.add_event_detect(19, GPIO.RISING, callback = prev)
GPIO.add_event_detect(5, GPIO.RISING, callback = volumeUp)
GPIO.add_event_detect(6, GPIO.RISING, callback = volumeDown)



t1 = Thread(target=readCard, args=(1,))
t2 = Thread(target=checkStatus)

t1.start()
t2.start()
