#! /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
import random
import shlex

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 = f"su -l {user} -c '{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 = f'AUDIODEV="{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] if pError else ""
			exitCode = pc.returncode

			try:
				if os.path.exists(self.fileToRemove) or os.path.islink(self.fileToRemove):
					os.remove(self.fileToRemove)
			except:
				pass

			self._manageToken('remove')

			try:
				if len(bellInfo) > 0:
					details = pError
					msg = f'Bell played. Id: {self.bellId} - Hour: {bellInfo[5]} - Name: {bellInfo[6]} - Exit Code: {exitCode} - Exit Details: {details}'
				else:
					msg = f'Bell played. Id: {self.bellId} - Error obtaining bell data'
				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:
				with open(self.configFile) as f:
					bellsConfig = json.load(f)

				bellData = bellsConfig.get(str(self.bellId))

				if bellData:
					duration = bellData["play"]["duration"]
					bellInfo.append(duration)
					startTime = bellData["play"].get("start", 0)
					bellInfo.append(startTime)

					soundOption = bellData["sound"]["option"]
					bellInfo.append(soundOption)
					soundPath = bellData["sound"]["path"]
					bellInfo.append(soundPath)

					validity = ""
					
					if bellData.get("validity", {}).get("active"):
						validity = bellData["validity"].get("value", "")
					
					bellInfo.append(validity)

					tmpTime = self._formatTime(bellData["hour"], bellData["minute"])
					bellInfo.append(tmpTime)
					bellInfo.append(bellData["name"])
			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])

		return currentDay in listDays

	#def _checkBellValidity

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

		if action == 'create':
			if not os.path.exists(self.tokenFolder):
				os.makedirs(self.tokenFolder, exist_ok=True)

			with open(self.tokenPath, 'a') as fd:

				fd.write(f"{self.bellId}\n")

			if bellInfo is not None:
				with open(self.newTokenPath, 'a') as fd:
					try:
						if len(bellInfo) > 0:
							fd.write(f"{self.bellId}###{bellInfo[6]}###{bellInfo[5]}###{bellInfo[0]}\n")
						else:
							fd.write(f"{self.bellId}\n")
					except:
						fd.write(f"{self.bellId}\n")
		else:
			if os.path.exists(self.tokenPath):
				try: os.remove(self.tokenPath)
				except: pass
			if os.path.exists(self.newTokenPath):
				try: os.remove(self.newTokenPath)
				except: pass

	#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:
					sessionProxy = bellBus.get_object('org.freedesktop.login1', item[4])
					sessionInterface = dbus.Interface(sessionProxy, dbus_interface='org.freedesktop.login1.Session')

					if str(sessionInterface.Get('org.freedesktop.login1.Session', 'State')) == "active":
						user = str(item[2])
						break
		except Exception:
			pass

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

		return user

	#def _getActiveUser

	def _getPlayCommand(self, bellInfo):

		if not bellInfo:
			return ""

		duration = bellInfo[0]
		startTime = bellInfo[1]
		soundOption = bellInfo[2]
		soundPath = bellInfo[3]

		self._getAudioDeviceOutput()

		cmdArgs = ["ffplay", "-nodisp", "-autoexit", "-loglevel", "error", "-ss", str(startTime)]
		if duration > 0:
			cmdArgs.extend(["-t", str(duration)])

		if duration > 0:
			fadeOut = int(duration) + int(startTime) - 2
			cmdArgs.extend(["-af", f"afade=in:st={startTime}:d=3,afade=out:st={fadeOut}:d=2"])

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

		if soundOption in ["file", "directory"]:
			cmdArgs.append(shlex.quote(soundPath))
		elif soundOption in ["url", "urlslist"]:
			soundPath = soundPath.replace("%", r"\%")
			cmdArgs.append(f'$(yt-dlp --get-url --format "bestaudio/best" "{soundPath}")')

		if self.audioDeviceCommand:

			return f"{self.audioDeviceCommand} " + " ".join(cmdArgs) + ";"

		return " ".join(cmdArgs) + ";"

	#def _getPlayCommand

	def _getSoundPath(self, option, soundPath):

		playPath = ""
		urlPlayedList = "/etc/bellScheduler/list_url_played"
		filePlayedList = "/etc/bellScheduler/list_file_played"

		for fPath in [urlPlayedList, filePlayedList]:
			if not os.path.exists(fPath):
				try:
					with open(fPath, 'w'): pass
				except: pass

		selectedItem = ""

		if option == "directory" and os.path.isdir(soundPath):
			playedFiles = set()
			if os.path.exists(filePlayedList):
				try:
					with open(filePlayedList, 'r', encoding='utf-8') as f:
						playedFiles = {line.strip() for line in f if line.strip()}
				except:
					pass

			validExtensions = ('.mp3', '.wav', '.ogg', '.m4a', '.flac', '.aac', '.wma', '.mp4')
			allFiles = []
			for root, _, files in os.walk(soundPath):
				for file in files:
					if file.lower().endswith(validExtensions):
						allFiles.append(os.path.join(root, file))

			if allFiles:
				if len(playedFiles) >= len(allFiles):
					try:
						with open(filePlayedList, 'w'): pass
						playedFiles.clear()
					except:
						pass

				availableFiles = [f for f in allFiles if os.path.basename(f) not in playedFiles]

				if not availableFiles:
					availableFiles = allFiles

				selectedItem = random.choice(availableFiles)

				try:
					with open(filePlayedList, 'a', encoding='utf-8') as f:
						f.write(f"{os.path.basename(selectedItem)}\n")
				except:
					pass

				extensionFile = selectedItem.split(".")[-1]
				playPath = os.path.join("/tmp", f"bellSelected.{extensionFile}")
				
				try:
					if os.path.exists(playPath) or os.path.islink(playPath):
						os.remove(playPath)
					os.symlink(selectedItem, playPath)
				except:
					playPath = selectedItem
				self.fileToRemove = playPath

		elif option == "urlslist" and os.path.isfile(soundPath):
			try:
				with open(soundPath, 'r', encoding='utf-8') as f:
					allUrls = [line.strip() for line in f if line.strip()]
			except:
				allUrls = []

			if allUrls:
				playedUrls = set()
				if os.path.exists(urlPlayedList):
					try:
						with open(urlPlayedList, 'r', encoding='utf-8') as f:
							playedUrls = {line.strip() for line in f if line.strip()}
					except:
						pass

				if len(playedUrls) >= len(allUrls):
					try:
						with open(urlPlayedList, 'w'): pass
						playedUrls.clear()
					except:
						pass

				availableUrls = [u for u in allUrls if u not in playedUrls]
				if not availableUrls:
					availableUrls = allUrls


				selectedItem = random.choice(availableUrls)
				playPath = selectedItem.replace("%", r"\%")

				try:
					with open(urlPlayedList, 'a', encoding='utf-8') as f:
						f.write(f"{selectedItem}\n")
				except:
					pass
		else:
			playPath = soundPath

		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 = f'AUDIODEV="{self.deviceId}"'
					self.audioDeviceCommand = f"{audioDriver} {audioDevice}"
			except:
				pass

	#def _getAudioDeviceOutput

	def _formatTime(self, bellHour, bellMinute):

		if bellHour < 10:
			bellHour = f"0{bellHour}"
		if bellMinute < 10:
			bellMinute = f"0{bellMinute}"
		
		return f"{bellHour}:{bellMinute}"

	#def _formatTime

if __name__ == "__main__":

	if len(sys.argv) > 1:
		bellId = sys.argv[1]
		bp = BellSchedulerPlayer(bellId)
	else:
		sys.exit(1)

#class BellSchedulerPlayer
