from __future__ import print_function
import logging
import os
import subprocess

LOG = logging.getLogger(__name__)


class AsteriskOutput(object):
    def __init__(self, config):
        self.config = config

    def play(self, audio_base, nodes=None):
        if not self.config.get("enabled", True):
            LOG.info("Asterisk output disabled; generated %s", audio_base)
            return
        selected = nodes or self.config.get("nodes") or []
        for node in selected:
            command = []
            values = {
                "binary": self.config.get("binary", "/usr/sbin/asterisk"),
                "node": str(node),
                "audio_base": audio_base,
            }
            for token in self.config.get("playback_command") or []:
                command.append(str(token).format(**values))
            if not command:
                raise RuntimeError("asterisk.playback_command is empty")
            LOG.info("Queueing audio on node %s", node)
            try:
                subprocess.check_call(command)
            except Exception as exc:
                LOG.error("Asterisk playback failed on node %s: %s", node, exc)

    def execute_dtmf(self, node, digits):
        binary = self.config.get("binary", "/usr/sbin/asterisk")
        command = [binary, "-rx", "rpt fun %s %s" % (node, digits)]
        subprocess.check_call(command)
