#!/usr/bin/python2

# License: GNU General Public License, version 2 or any later version
#
# Modified by: rusty_robot
#
# Common module for asoundconf and asoundconf-gtk:
# - get card and device list

import re, os.path


class SndCardInfo(object):
	def __init__(self):
		self.card_num = -1
		self.id_ = ''
		self.name = ''


class SndPcmInfo(object):
	def __init__(self):
		self.card_num = -1
		self.dev_num = -1
		self.id_ = ''
		self.name = ''


def parse_cards():
	'''Get card info from /proc/asound/cards'''

	cardspath = '/proc/asound/cards'
	if not os.path.exists(cardspath):
		raise IOError(cardspath + ' does not exist')
	procfile = open(cardspath, 'rb')

	cardline = re.compile('^\s*(\d+)\s*\[(\w+)\s*\].*-\s(.*)$') # capture card number, id and name
	card_lines = []

	lines = procfile.readlines()
	for l in lines:
		if cardline.match(l):
			groups = cardline.match(l).groups()
			c = SndCardInfo()
			c.card_num = int(groups[0])
			c.id_  = groups[1].strip()
			c.name = groups[2].strip()
			card_lines.append(c)

	return card_lines


def parse_devices():
	'''Get device numbers and names from /proc/asound/pcm'''

	devspath = '/proc/asound/pcm'
	if not os.path.exists(devspath):
		raise IOError(devspath + ' does not exist')
	procfile = open(devspath, 'rb')

	devnum = re.compile('(\d+)-(\d+)')
	dev_lines = []

	lines = procfile.readlines()
	for l in lines:
		fields = l.split(':')
		if len(fields) >= 3:
			if devnum.match(fields[0]):
				groups = devnum.match(fields[0]).groups()
				d = SndPcmInfo()
				d.card_num = int(groups[0])
				d.dev_num  = int(groups[1])
				d.id_  = fields[1].strip()
				d.name = fields[2].strip()
				dev_lines.append(d)

	return dev_lines