#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Fri May 24 17:16:54 2019

@author: georges Evesque
jukebox program using appjar GUI and mplayerpy for the play part
Update :14/06/2019 clean up a listle bit the widgets management
management of widgets (enable/disable depending on the use of the jukebox)
"""
import os
import time
from appJar import gui
import mplayer
from random import *
import RPi.GPIO as GPIO
import unicodedata
#********************* Start the home cinema via IR commands ****************
os.system("start_jukebox")
time.sleep (3)# let time to the amp to change input channel
#**** set GPIO pin for periodical heartbit command to arduino **************
heartbeat_pin=27   # 3;3 v to Arduino nano every 9 seconds for 1 second
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(heartbeat_pin,GPIO.OUT,initial=0)
#************* Init player status *****************************
player_status=0 # 0= not playing,1= Shuffle,2= sequence
mod_plst=0
player=mplayer.Player()
gl_file=[] #*****global file to play
pl_file= [] #****playlist content file
playlst="" # ***** playlist name
dir_p=""
tsk_count=0
nb_song=0 # ***** number of song in the list (gl_file)
count=1 # ********* number of test for Taskman to check the on going song
pos= 0 #********* row position for widgets
p_vol=20# starting playing level (the default startting level of the Home cinema Amp)
dir="/home/pi/Music/"
color="lime"
ptr_song=0
max_ptr_song=0
list_number=[]  # list of x last played songs (x=length playlist//5) to avoid redundancy in random songs during shuffle
cur_ptr=0
for i in range (300):
    list_number.append(0) # max 1500 (1500//5) song files (but it can be more ....)
#******************************** Taskman ****************************
#**********************the heart of the programm:
# generate heart beat to Arduino
# check the length of the current song
# update the progrees bar of the song
def taskman():# generate periodic tasks on a 1 second basis
    global tsk_count 
    global color
    tsk_count +=1
    global player_status
    global count
    #********** every second ***************
    #************* monitoring player *******
    if (player_status >0):
        if (player_status==1):
            #***fash the shuffle button
            if (color=="lime"):
                color="green"
            else:
                color="lime"
            app.setButtonBg("Shuffle",color)
        if (count==0):
            a=player.time_pos
            b=player.length
            if (a!=None and b!=None):
                prog=(a*100//b)
                app.setMeter("progress",prog)  #progress bar      
            else:
                if (player_status==1):#************ case shuffle_player *********
                    l_shuffle()
                if (player_status==2):
                    player_status=0
                    app.setMeter("progress",0)
        else:
            count-=1
    if (app.getLabel("playlists") !="All Songs"):
        disable ("Mod. Playlist")
    else:
        enable ("Mod. Playlist")
    # generate periodic tasks on a 9 seconds basis
    if (tsk_count==9):
        tsk_count=0
        GPIO.output(heartbeat_pin,GPIO.HIGH)#************** send heartbit command to arduino ***************
    if (tsk_count==1):
        GPIO.output(heartbeat_pin,GPIO.LOW)#*************** and stop the command to Arduino *******
def rand_song(): # generate random number of file to be played in shufflz mode
    global nb_song
    global ptr_song
    global list_number
    global max_ptr
    global cur_ptr
    flg=1
    n=0 
    while flg==1:
        flg=0
        n=randint(0,nb_song)
        for i in list_number:
            if (n==i):
                flg=1
    list_number[cur_ptr]=n
    ptr_song=n
    cur_ptr +=1
    if (cur_ptr==max_ptr+1):
        cur_ptr=0
def m_plst():
    global mod_plst
    if (mod_plst==0):
        mod_plst=1
        app.setButton("Mod. Playlist","Arret Modif.")
        disable( "Playlist +")
    else:
        mod_plst=0
        app.setButton("Mod. Playlist","Mod. Playlist")
        disable( "Playlist +")
def arret(button):
    os.system("stop_jukebox") # bash to Power off home cinema
    time.sleep(5)
    player.quit()
    app.stop()
    time.sleep(2)
    os.system("sudo shutdown -h now") #suicide !!!!!!!!
def l_shuffle():
    global gl_file
    global nb_song
    global ptr
    global max_ptr
    global ptr_song
    global cur_ptr
    app.setMeter("progress",0)
    nb_song=len(gl_file)-1
    max_ptr=(nb_song//5)
    rand_song()
    song =gl_file [ptr_song]    
    groupe= song.split("/") [0]   
    dir_p="/home/pi/Music/"+groupe
    song=song.split("/") [1]
    song =song.split(".") [0]  
    play_song(song,groupe,dir_p)
def shuffle(button):
    global player_status
    player_status=1
    enable("Shuffle")
    enable ("Stop")
    enable ("Pause")
    enable ("Volume +")
    enable ("Volume -")
    l_shuffle()
def pause(button):
    global player_status
    if (player_status >0):
        player.pause()   
def stop(button):
    global player_status
    app.setButtonBg("Shuffle","lime")
    if (player_status>0):
        player.stop()
        app.setLabel("morceau","")
        app.setLabel("artist","")
        player_status=0
        app.setMeter("progress",0)
        disable ("Stop")
        disable ("Pause")
def volp(button):
    global p_vol
    os.system("irsend SEND_ONCE jukebox KEY_VOLUMEUP") #send LIRC commande
    disable ("Volume +") 
    p_vol+=1
    if (p_vol>50):
        p_vol=50
    app.setMeter("v_p",2*p_vol)
    time.sleep(0.3)
    enable ("Volume +")
def volm(button): 
    global p_vol
    os.system("irsend SEND_ONCE jukebox KEY_VOLUMEDOWN") #send LIRC commande
    disable ("Volume -") 
    p_vol-=1
    if (p_vol<0):
        p_vol=0
    app.setMeter("v_p",2*p_vol)
    time.sleep(0.3)
    enable ("Volume -")
def play_song(name,groupe,dir_p):
    global count
    app.setLabel("morceau",name)
    app.setLabel("artist",groupe)    
    name=dir_p+"/"+name+".mp3"
    count=2
    player.loadfile(name);
def list_group():#************************ get selected artist ******************
    global dir_p
    global s_groupe
    global sel_item
    global gl_file
    groupe=""
    sel_item="groupe"
    l_song=[]
    s_groupe=app.getListBox("Groupes") [0]
    app.setLabel("artist",s_groupe)
    app.clearListBox("Chansons",callFunction=False)
    for i in gl_file:
        chanson=i [0:len(i)-6]
        groupe=chanson.split("/")[0]
        if (groupe==s_groupe):
            song=(chanson.split("/")[1])
            l_song.append(song)
    l_song.sort(key=str.lower)
    app.addListItems("Chansons",l_song)
    if (mod_plst==0):
        enable("Shuffle")
        enable ("Stop")
        enable ("Pause")
        enable ("Volume +")
        enable ("Volume -") 
def click_song():#******************** get selected song *************************
    global dir
    global song
    global dir
    global player_status
    global mod_plst
    global gl_file
    song=app.getListBox("Chansons") [0]
    for i in gl_file:
        if (i.find(song)>0):
            break
    chanson=i [0:len(i)-6]
    groupe=chanson.split("/")[0] 
    dir_p="/home/pi/Music/"+groupe
    chanson=chanson.split("/")[1]
    if (mod_plst==0): # If in playing mode
        if (player_status !=1):
            player_status=2
        enable("Shuffle")
        enable ("Stop")
        enable ("Pause")
        enable ("Volume +")
        enable ("Volume -")
        play_song(song,groupe,dir_p)
    else:#**************** adding song to a playlist **************
        flg=0
        for i in pl_file:# check if song not already in the playlist
            if ((i.find(song)>=0) and (i.find(groupe)>=0)):
                disable("Playlist +")
                flg=1
                break
        if (flg==0):
            song=groupe+"/"+song+".mp3"
def sel_plist():
    global playlst
    global sel_item
    global gl_file
    global pl_file
    global nb_song
    global mod_plst
    gl_file= []
    sel_item="playlist"
    playlst=app.getListBox("Playlists") [0]
    if (mod_plst==0):
        app.setLabel("playlists",playlst)
        if (playlst!="All Songs"):       
            #*****************************populate artit and song listboxes **********
            f=open("/home/pi/Playlists/"+playlst+".txt","r")
            gl_file=f.readlines()
            f.close()
            pop_lst_boxes()
            enable("Shuffle")
            enable ("Stop")
            enable ("Pause")            
            enable ("Volume +")
            enable ("Volume -")
            disable( "Playlist +")          
        else:
            f=open("/home/pi/Documents/list.txt","r")
            gl_file=f.readlines()
            f.close()
            nb_song=len(gl_file)-1
            pop_lst_boxes() 
            enable("Shuffle")
            enable ("Stop")
            enable ("Pause")
            enable ("Volume +")
            enable ("Volume -")
            disable( "Playlist +")
    else:
        #*****************************get list of the given playlist **********
        f=open("/home/pi/Playlists/"+playlst+".txt","r")
        pl_file=f.readlines()# populate the playlist's songs
        f.close()
        f=open("/home/pi/Documents/list.txt","r")
        gl_file=f.readlines()
        f.close()
        disable("Shuffle")
        disable ("Stop")
        disable ("Pause")            
        disable ("Volume +")
        disable ("Volume -") 
        enable ("Playlist +")
def plstp():#add song to a play lsit
    global playlst
    global song
    global mod_plst
    if (mod_plst==1):
        f=open ("/home/pi/Playlists/"+playlst+".txt","a")
        f.write(song+"\r\n")
        f.close()
def pop_lst_boxes():
    global dir
    global gl_file
    l_song=[]
    l_groupe=[]
    app.clearListBox("Chansons",callFunction=False)
    app.clearListBox("Groupes",callFunction=False)
    for i in gl_file:
        chanson=i [0:len(i)-6]
        groupe=chanson.split("/")[0]
        flg=0
        for j in l_groupe:
            if (j==groupe):
                flg=1
                break
        if (flg==0):
            l_groupe.append(groupe)
        song=(chanson.split("/")[1])
        l_song.append(song)
    l_groupe.sort(key=str.lower)
    l_song.sort(key=str.lower)
    app.addListItems("Groupes",l_groupe)
    app.addListItems("Chansons",l_song)
def enable (btn):
    app.setButtonBg(btn,"lime")
    app.enableButton(btn)
def disable (btn):
    app.setButtonBg(btn,"red")
    app.disableButton(btn)
#*************************************Setting up Widgets **********************
app=gui("Jukebox","fullscreen")
app.setBg("gold")
app.setFont(18)
p_empty=0
pos=1
#****button shuffle*****
app.addButton("Shuffle",shuffle,pos,0)
app.setButtonWidth("Shuffle",10)
app.setButtonBg("Shuffle","red")
pos+=1
#****button pause*****
app.addButton("Pause",pause,pos,0)
app.setButtonWidth("Pause",10)
app.setButtonBg("Pause","red")
pos+=1
#****button Stop*****
app.addButton("Stop",stop,pos,0)
app.setButtonWidth("Stop",10)
app.setButtonBg("Stop","red")
pos+=1
#*****empty row*****
app.addLabel(str(p_empty),pos,0)
app.setLabelHeight(str(p_empty),1)
p_empty+=1
pos+=1
#****button Volume +*****
app.addButton("Volume +",volp,pos,0)
app.setButtonWidth("Volume +",10)
pos+=1
#****Splitmeter*****
app.addMeter("v_p",pos,0)
app.setMeterWidth("v_p",10)
app.setMeterFill("v_p","green")
app.setMeter("v_p",2*p_vol)
pos+=1
#****Volume -*****
app.addButton("Volume -",volm,pos,0)
app.setButtonWidth("Volume -",10)
pos+=1
#*****empty row*****
app.addLabel(str(p_empty),pos,0)
app.setLabelHeight(str(p_empty),1)
p_empty+=1
pos +=1
#*****empty row*****
app.addLabel(str(p_empty),pos,0)
app.setLabelHeight(str(p_empty),1)
p_empty+=1
pos +=1
#****label quitter*****
app.addLabel("Quitter","Arrêt",pos,0)
app.setLabelBg("Quitter","red")
#****Colum 1*****
app.addButton ("Mod. Playlist",m_plst,pos,1)
app.setButtonWidth("Mod. Playlist",10)
pos+=1
#****Button Arrêt*****
app.addButton("Arrêt Jukebox",arret,pos,0)
app.setButtonBg("Arrêt Jukebox","red")
app.setButtonWidth("Arrêt Jukebox",10)
#****column 1*****
app.addButton("Playlist +",plstp,pos,1)
app.setButtonWidth("Playlist +",10)
pos+=1
#*****empty row*****
app.addLabel(str(p_empty),pos,0)
app.setLabelHeight(str(p_empty),1)
p_empty+=1
pos+=1
#****Colum 1*****
app.addLabel ("col_pl","Playlist",0,1)
app.setLabelBg ("col_pl","Turquoise")
#**************************
lbp=app.addListBox("Playlists","",3,1,rowspan=4)
app.setListBoxBg("Playlists","royalblue")
app.setListBoxWidth("Playlists",10)
app.setListBoxHeight("Playlists",3)
app.getListBoxWidget("Playlists").config(font=("Verdana 20"))
#***************************
app.addLabel ("playlists","All Songs",1,1)
app.setLabelBg("playlists","yellow")
app.getLabelWidget("playlists").config(font=("Verdana 14"))
#***************************
lbg=app.addListBox("Groupes","",3,2,rowspan=pos-3)
app.setListBoxBg("Groupes","royalblue")
app.getListBoxWidget("Groupes").config(font=("Verdana 14"))
#***************************
app.addLabel ("artist","Groupe",1,2)
app.setLabelBg("artist","yellow")
app.getLabelWidget("artist").config(font=("Verdana 14"))
#***************************
app.addLabel ("col_art","Groupe",0,2)
app.setLabelBg ("col_art","Turquoise")
#***************************
lbc=app.addListBox("Chansons","Chanson",3,3,rowspan=pos-3)
app.setListBoxBg("Chansons","royalblue")
app.getListBoxWidget("Chansons").config(font=("Verdana 14"))
#***************************
app.addLabel ("morceau","",1,3)
app.setLabelBg("morceau","yellow")
app.getLabelWidget("morceau").config(font=("Verdana 14"))
#***************************
app.addLabel ("col_song","Chanson",0,3)
app.setLabelBg ("col_song","Turquoise")
#***********************************************
lbg.bind('<ButtonRelease-1>',lambda *args:list_group())
lbc.bind('<ButtonRelease-1>',lambda *args:click_song())
lbp.bind('<ButtonRelease-1>',lambda *args:sel_plist())
app.addSplitMeter("progress",2,2,colspan=2)
app.setMeterFill("progress",["orangered","green"])
#****etiquette play******
app.addLabel("play","Play ",0,0)
app.setLabelBg("play","turquoise")
#********************* set up widgets ***************
enable("Shuffle")
enable ("Stop")
enable ("Pause")
enable ("Volume +")
enable ("Volume -")
disable( "Playlist +")
#******************* start taskman => periodic 1 sec event **********************
app.registerEvent(taskman)
app.setPollTime(1000)
#****************************Titlles list creation******************************
songs=[]
files=0
texte=""
index=0
flg_mod=0
chanson=""
groupe=""
n_groupe=""
groupes=[]
a=0
f=open("/home/pi/Documents/list.txt","r")
gl_file=f.readlines()
f.close()
#************************************************ populate listboxes ******************************
app.setLabel("playlists","All Songs")
pop_lst_boxes()
#********** populate the playlists name **************
f=open("/home/pi/Documents/playlists.txt","r")
fichier=f.readlines()
f.close()
fichier.sort()
for i in fichier:
    i=i [0:len(i)-2]
    app.addListItem("Playlists",i)
#************************************ Main ***************************************
app.go() 
