from random import random

from sendinel import settings

LINUX_AVAILABLE = False

try:
    import grp
    import os
    import pwd
    import shutil
    from subprocess import Popen, PIPE

    from hashlib import md5
    
    LINUX_AVAILABLE = True
    
except ImportError:
    print "Warning: Linux is required for voicecall functionality"
    
import time
import re

# TODO Test this completey!

class Voicecall:
    """
        This class takes responsibility for sending voicecalls and short messages
        through the asterisk telephony server
    """
    def __init__(self):
        self.asterisk_user = settings.ASTERISK_USER
        self.asterisk_group = settings.ASTERISK_GROUP
        self.asterisk_spool_dir = settings.ASTERISK_SPOOL_DIR  
        self.asterisk_extension = settings.ASTERISK_EXTENSION
        self.asterisk_sip_account = settings.ASTERISK_SIP_ACCOUNT
        self.asterisk_festivalcache = settings.FESTIVAL_CACHE
        self.asterisk_datacard = settings.ASTERISK_DATACARD 
        self.salutation = settings.CALL_SALUTATION

    def create_voicefile(self, text):
        """
            Create a soundfile for the given text, using a TTS engine
    
            @param  text:   the text to be read
            @type   text:   String
    
            @return The full file name of the sound file containing the text
        """

        text_hash = md5(text).hexdigest()
        filename = "%s/%s.ulaw" % (self.asterisk_festivalcache, text_hash)
        if not os.path.exists(filename):
            args = "-o %s -otype ulaw -" % (filename)
            
            if str(settings.LANGUAGE_CODE) == "en-us":