#!/usr/bin/python
"""
Extension to send a Fax
"""
#  Copyright (C) 2004  Henning Jacobs <henning@srcco.de>
#
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.
#
#  $Id: faxtowrapper.py 82 2004-07-11 13:01:44Z henning $

import sys
import os
import Preferences

def faxto(recipient, telnumber):
    faxprog = Preferences.get("client.faxto_program")
    if sys.platform == 'win32':
        if not faxprog:
            # Get default fax-application from Windows-Registry:
            # TODO: Howto fax on Windows????
            import _winreg
            handle = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,
                'SOFTWARE\Classes\\faxto\shell\open\command')
            valname, faxprog, valtype = _winreg.EnumValue(handle, 0)
        args = faxprog.split(' ')
        # Remove dbl-quotes if any:
        if args[0][0] == '"' and args[0][-1] == '"':
            args[0] = args[0][1:-1]
        args[0] = os.path.abspath(args[0])    
        for i in range(1, len(args)):
            args[i] = args[i].replace('%1', recipient)
            args[i] = args[i].replace('%2', telnumber)
        os.spawnv(os.P_NOWAIT, args[0], args)
    else:
        if not faxprog:
            # Ugly fallback:
            # (xterm, vi and fax should be available on every UNIX-machine):
            faxprog = 'xterm | -e | sh | -c | vi /tmp/pycocuma_fax.txt && fax send %2 /tmp/pycocuma_fax.txt'
            args = faxprog.split(' | ')
        else:
            args = faxprog.split(' ')
        for i in range(1, len(args)):
            args[i] = args[i].replace('%1', recipient)
            args[i] = args[i].replace('%2', telnumber)
        os.spawnvp(os.P_NOWAIT, args[0], args)

