#! /usr/bin/python3

import os
import subprocess
import shutil
import dbus
import sys
import json
from datetime import datetime, date,timedelta
import syslog
import time

class BellSchedulerPlayer:

	def __init__(self,bellId):

		self.bellId=bellId
		self.configDir=os.path.expanduser("/etc/bellScheduler/")
		self.configFile=os.path.join(self.configDir,"bell_list")
		self.tokenFolder="/tmp/.BellScheduler"
		self.tokenPath=os.path.join(self.tokenFolder,'bellscheduler-token')
		self.newTokenPath=os.path.join(self.tokenFolder,'newbellscheduler-token')
		self.audioDeviceConfigFile=os.path.join(self.configDir,"audio_device")
		self.audioDeviceCommand=""
		self.deviceId=""
		self.playBell()

	#def__init__

	def playBell(self):

		self.fileToRemove=""
		abort=False

		bellInfo=self._readCurrentBell()
		if len(bellInfo)>0 and bellInfo[4]!="":
			if not self._checkBellValidity(bellInfo[4]):
				abort=True

		if abort:
			sys.exit(1)
		else:
			self._manageToken('create',bellInfo)
			user=self._getActiveUser()

			playCommand=self._getPlayCommand(bellInfo)
			
			if user!="":
				cmd="su -l %s -c '%s'"%(user,playCommand)
			else:
				cmd=playCommand

			startTime=time.perf_counter()
			pc=subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
			pError=pc.communicate()[1].decode().split("\n")
			endTime=time.perf_counter()
			totalTime=endTime-startTime
			
			if len(pError)>1:
				if self.audioDeviceCommand!="" and self.deviceId!="default":
					exitCode=pc.returncode
					if exitCode !=-15 and totalTime<5:
						oldCommand='AUDIODEV="%s"'%self.deviceId
						newCommand='AUDIODEV="default"'
						cmd=cmd.replace(oldCommand,newCommand)
						pc=subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
						pError=pc.communicate()[1].decode().split("\n")
						if len(pError)>1:
							pError.pop()
				else:
					pError.pop()
			
			pError=pError[-1]
			exitCode=pc.returncode

			try:
				if os.path.exists(self.fileToRemove):
					os.remove(self.fileToRemove)
			except:
				pass
			
			self._manageToken('remove')
			try:
				if len(bellInfo)>0:
					details=pError	
					msg='Bell played. Id: %s - Hour: %s - Name: %s - Exit Code: %s - Exit Details: %s'%(self.bellId,bellInfo[5],bellInfo[6],exitCode,details)
				else:
					msg='Bell played. Id: %s - Error obtaining bell data'%self.bellId
				syslog.openlog("BELL-SCHEDULER-PLAYER")
				syslog.syslog(msg)
			except Exception as e:
				pass
			
			sys.exit(0)
		
	#def playBell

	def _readCurrentBell(self):

		bellInfo=[]

		if os.path.exists(self.configFile):
			try:
				f=open(self.configFile)
				bellsConfig=json.load(f)
				for item in bellsConfig:
					if item==str(self.bellId):
						duration=bellsConfig[item]["play"]["duration"]
						bellInfo.append(duration)
						try:
							startTime=bellsConfig[item]["play"]["start"]
						except:
							startTime=0
						
						bellInfo.append(startTime)
						soundOption=bellsConfig[item]["sound"]["option"]
						bellInfo.append(soundOption)
						soundPath=bellsConfig[item]["sound"]["path"]
						bellInfo.append(soundPath)
						try:
							if bellsConfig[item]["validity"]["active"]:
								validity=bellsConfig[item]["validity"]["value"]
							else:
								validity=""
						except:
							validity=""
						bellInfo.append(validity)
						tmpTime=self._formatTime(bellsConfig[item]["hour"],bellsConfig[item]["minute"])
						bellInfo.append(tmpTime)
						bellInfo.append(bellsConfig[item]["name"])
						break;
			except:
				pass

		return bellInfo

	#def _readCurrentBell

	def _checkBellValidity(self,validity):

		currentDay=date.today().strftime('%d/%m/%Y')
		
		listDays=[]
		tmp=validity.split("-")
		if len(tmp)>1:
			date1=datetime.strptime(tmp[0],'%d/%m/%Y')
			date2=datetime.strptime(tmp[1],'%d/%m/%Y')
			delta=date2-date1
			for i in range(delta.days + 1):
				tmpDay=(date1 + timedelta(days=i)).strftime('%d/%m/%Y')
				listDays.append(tmpDay)
		else:
			listDays.append(tmp[0])
		
		if currentDay in listDays:
			return True
		else:
			return False

	#def _checkBellValidity

	def _manageToken(self,action,bellInfo=None):

		if action=='create':
			if not os.path.exists(self.tokenFolder):
				os.mkdir(self.tokenFolder)

			with open(self.tokenPath,'a') as fd:
				fd.write("%s\n"%(self.bellId))
			
			if (bellInfo!=None):
				with open(self.newTokenPath,'a') as fd:
					try:
						if len(bellInfo)>0:
							fd.write("%s###%s###%s###%s\n"%(self.bellId,bellInfo[6],bellInfo[5],bellInfo[0]))
						else:
							fd.write("%s\n"%(self.bellId))
					except:
						fd.write("%s\n"%(self.bellId))
			
		else:
			if os.path.exists(self.tokenPath):
				os.remove(self.tokenPath)
			
			if os.path.exists(self.newTokenPath):
				os.remove(self.newTokenPath)
			

	#def _manageToken

	def _getActiveUser(self):

		user=""

		try:
			bellBus=dbus.SystemBus()
			bellProxy=bellBus.get_object('org.freedesktop.login1','/org/freedesktop/login1')
			dbusBell=dbus.Interface(bellProxy,dbus_interface='org.freedesktop.login1.Manager')
			currentSessions=dbusBell.ListSessions()
			if len(currentSessions)>0:
				for item in currentSessions:
					uid=int(item[0])
					user=str(item[2])
					cmd='loginctl session-status %s | grep "active" | grep -v "grep"'%uid
					p=subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE)
					pout=p.communicate()[0].decode()
					if len(pout)>0:
						break
		except Exception as e:
			pass

		if user=="sddm":
			user=""
		
		return user

	#def _getActiveUser

	def _getPlayCommand(self,bellInfo):

		playCommand=""
		
		if len(bellInfo)>0:
			duration=bellInfo[0]
			startTime=bellInfo[1]
			soundOption=bellInfo[2]
			soundPath=bellInfo[3]

			self._getAudioDeviceOutput()

			if duration>0:
				fadeOut=int(duration)+int(startTime)-2
				fadeEffects='-af afade=in:st=%s:d=3,afade=out:st=%s:d=2'%(str(startTime),str(fadeOut))
				cmd="%s ffplay -nodisp -autoexit -loglevel error -ss %s -t %s"%(self.audioDeviceCommand,str(startTime),str(duration))
			else:
				fadeEffects=''
				cmd="%s ffplay -nodisp -autoexit -loglevel error -ss %s"%(self.audioDeviceCommand,str(startTime))

			if soundOption in ["directory","urlslist"]:
				soundPath=self._getSoundPath(soundOption,soundPath)

			if soundOption in ["file","directory"]:
				soundPath=soundPath.replace("'","'\\''")
				cmd=cmd+' "'+ soundPath +'" '+fadeEffects+';'
			elif sound_option in ["url","urlslist"]:
				soundPath=soundPath.replace("%","\%")
				cmd=cmd+ ' $(youtube-dl -g "'+soundPath+'" | sed -n 2p) '+fadeEffects+';'	
			
			playCommand=cmd

		return playCommand

	#def _getPlayCommand

	def _getSoundPath(self,option,soundPath):

		playPath=""
		cmd='randomaudiofile "%s"'%soundPath
		p=subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE)
		pout=p.communicate()[0].decode().strip()

		if pout!="":
			if option=="directory":
				extensionFile=pout.split(".")[-1]
				tmpFile="bellSelected.%s"%extensionFile
				playPath=os.path.join("/tmp",tmpFile)
				try:
					shutil.copy(pout,playPath)
				except :
					pass
				self.fileToRemove=playPath
			else:
				playPath=pout

		return playPath

	#def _getSoundPath

	def _getAudioDeviceOutput(self):

		self.audioDeviceCommand=""
		self.deviceId=""

		if os.path.exists(self.audioDeviceConfigFile):
			try:
				with open(self.audioDeviceConfigFile,'r') as fd:
					self.deviceId=fd.readline().strip()
					audioDriver='SDL_AUDIODRIVER="alsa"'
					audioDevice='AUDIODEV="%s"'%self.deviceId
					self.audioDeviceCommand="%s %s"%(audioDriver,audioDevice)
			except:
				pass

	#def _getAudioDeviceOutput

	def _formatTime(self, bellHour, bellMinute):

		if bellHour<10:
			bellHour="0%s"%bellHour
		if bellMinute<10:
			bellMinute="0%s"%bellMinute

		formatTime="%s:%s"%(bellHour,bellMinute)

		return formatTime

	#def formatTime

#class BellSchedulerPlayer

if __name__=="__main__":

	bellId=sys.argv[1]
	bp=BellSchedulerPlayer(bellId)

