"""This code is a collection of functions that compute acoustic properties
and cache them.
"""

import numpy

from gmisclib import cache as CC
from gmisclib import gpkmisc
from gpk_voicing import emphasis as E
from gpk_voicing import dirty_io
import gpkimgclass

ROOT = '/tmp/cached_loudness'

def emphasis(data, DT, cache_info=None):
	"""Compute loudness density ('emphasis') from a numpy array.   Cache the result.
	"""
	ci = None
	if cache_info is not None:
		assert isinstance(cache_info, CC.cache_info)
		ci = cache_info.addinfo(DT, data.get('_NAME', '?'), 'emphasis', mod=E)
		try:
			return ci.load()
		except ci.Errors:
			pass
	e = E.simple_emphasis(data.column(0), data.dt(), DT)
	if ci is not None:
		ci.dump(e)
	return e


def emphasis_f_name(fname, DT, root=ROOT):
	"""Compute loudness density ('emphasis') from a file.   Cache the result.
	"""
	nm, ch = dirty_io.splitname(fname)
	cacheinfo = CC.cache_info(root=root, fname=nm, info=(DT, ch, 'emphasis_f_name'), mod=(E,dirty_io))
	try:
		return cacheinfo.load()
	except cacheinfo.Errors:
		pass
	data = dirty_io.wav_read(nm, channel=ch)
	e = E.simple_emphasis(data.column(0), data.dt(), DT)
	hdr = data.hdr.copy()
	hdr['CDELT2'] = DT
	del hdr['NAXIS2']
	return cacheinfo.dump(gpkimgclass.gpk_img(hdr, numpy.transpose([e])))


def sb_loudness_f_name(fname, DT, root=ROOT):
	"""Compute loudness density ('emphasis') from a file.   Cache the result.
	"""
	nm, ch = dirty_io.splitname(fname)
	cacheinfo = CC.cache_info(root=root, fname=nm, info=(DT, ch, 'sb_loudness_f_name'), mod=(E,dirty_io))
	try:
		return cacheinfo.load()
	except cacheinfo.Errors:
		pass
	data = dirty_io.wav_read(nm, channel=ch)
	e = E.speechband_loudness(data.column(0), data.dt(), DT)
	hdr = data.hdr.copy()
	hdr['CDELT2'] = DT
	del hdr['NAXIS2']
	return cacheinfo.dump(gpkimgclass.gpk_img(hdr, numpy.transpose([e])))


