#!/usr/bin/env python

# This file is part of Window-Switch.
# Copyright (c) 2009-2013 Antoine Martin <antoine@nagafix.co.uk>
# Window-Switch is released under the terms of the GNU GPL v3

from winswitch.util.simple_logger import Logger
logger = Logger("sound_util")
debug_import = logger.get_debug_import()

debug_import("os, subprocess")
import os

debug_import("common")
from winswitch.util.common import save_binary_file, remove_local_env, is_valid_exe
debug_import("globals")
from winswitch.globals import WIN32, OSX
debug_import("which")
from winswitch.util.which import which

pactl_bin = which("pactl")
has_pulseaudio = None
def detect_pa():
	if WIN32 or not is_valid_exe(pactl_bin):
		return	False
	(status, _) = pactl_output("stat")
	return status==0

def has_pa():
	global has_pulseaudio
	if has_pulseaudio is None:
		has_pulseaudio = detect_pa()
	return has_pulseaudio


def pactl_output(pactl_cmd):
	#ie: "pactl list"
	cmd = [pactl_bin, pactl_cmd]
	try:
		from winswitch.util.process_util import get_output
		code, out, _ = get_output(cmd)
		return  code, out
	except Exception, e:
		logger.serror("failed to get list of devices using %s: %s" % (cmd, e))
		return  -1, None



def get_audio_tagging_env(session, server_or_client, description=None):
	"""
		This is called audio-tagging in PulseAudio, see:
		http://pulseaudio.org/wiki/ApplicationProperties
		http://0pointer.de/blog/projects/tagging-audio.html
	"""
	icon_data = session.get_window_icon_data() or session.get_default_icon_data()
	if not icon_data:
		from winswitch.ui.icons import getraw
		icon_data = getraw("winswitch")
	if server_or_client:
		#server: re-use the session icon file
		from winswitch.util.config import get_session_icon_filename
		icon_path = get_session_icon_filename(session.display, session.user)
	else:
		from winswitch.util.file_io import get_session_temp_dir
		icon_path = os.path.join(get_session_temp_dir(), "%s.icon" % session.ID)
	save_binary_file(icon_path, icon_data)
	if not description:
		description = "winswitch: %s" % session.name
	return {
			"PULSE_PROP_application.name" : description,
			"PULSE_PROP_media.role" : "music",
			"PULSE_PROP_application.icon_name" : icon_path
			}

def get_session_sound_env(session, server_or_client, description=None):
	"""
	Adds the audio tagging env to the session.env
	"""
	#just to trim things a bit (there are useless to gst_launch_wrapper and clutter the log file):
	env = remove_local_env(session.env.copy())
	if has_pa():
		for k,v in get_audio_tagging_env(session, server_or_client, description).items():
			env[k] = v
	return	env










def get_pa_device_options(monitors=False, input_or_output=None, ignored_devices=["bell-window-system"]):
	"""
	Finds the list of devices, monitors=False allows us to filter out monitors
	(which could create sound loops if we use them)
	set input_or_output=True to get inputs only
	set input_or_output=False to get outputs only
	set input_or_output=None to get both
	Same goes for monitors (False|True|None)
	Returns the a dict() with the PulseAudio name as key and a description as value
	"""
	if WIN32 or OSX:
		return {}
	status, out = pactl_output("list")
	if status!=0 or not out:
		return  {}
	device_class = None
	device_description = None
	name = None
	devices = {}
	for line in out.splitlines():
		#print("line=%s" % line)
		if not line.startswith(" ") and not line.startswith("\t"):		#clear vars when we encounter a new section
			if name and device_class:
				if name in ignored_devices:
					continue
				#print("get_pa_device_options() found name=%s, device_class=%s" % (name, device_class))
				#Verify against monitor flag if set:
				if monitors is not None:
					is_monitor = device_class=='"monitor"'
					if is_monitor!=monitors:
						continue
				#Verify against input flag (if set):
				if input_or_output is not None:
					is_input = name.find("input")>=0
					if is_input is True and input_or_output is False:
						continue
					is_output = name.find("output")>=0
					if is_output is True and input_or_output is True:
						continue
				if not device_description:
					device_description = name
				devices[name] = device_description
			name = None; device_class = None
		line = line.strip()
		if line.startswith("Name: "):
			name = line[len("Name: "):]
		if line.startswith("device.class = "):
			device_class = line[len("device-class = "):]
		if line.startswith("device.description = "):
			device_description = line[len("device.description = "):].strip('"')
	return devices



debug_import("end")
