#!/usr/bin/env python
#
# (c) Copyright 2003-2005 Hewlett-Packard Development Company, L.P.
#
# 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.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
#
# Author: Don Welch
#
# Thanks to Henrique M. Holschuh <hmh@debian.org> for various security patches
#

_VERSION = '1.5'

# Std Lib
import sys, socket, os, os.path, getopt, signal, atexit
import ConfigParser, pwd, socket

# Local
from base.g import *
from base.msg import *
import base.utils as utils
import base.async_qt as async
from base import service

app = None
sendfax = None
client = None

# PyQt
if not utils.checkPyQtImport():
    sys.exit(0)

from qt import *

# UI Forms
from ui.faxsendjobform import FaxSendJobForm


class fax_client(async.dispatcher):

    def __init__(self):
        async.dispatcher.__init__(self)
        self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
        self.connect((prop.hpssd_host, prop.hpssd_port)) 
        self.in_buffer = ""
        self.out_buffer = ""
        self.fields = {}
        self.data = ''
        self.error_dialog = None
        self.signal_exit = False

        # handlers for all the messages we expect to receive
        self.handlers = {
                        'eventgui' : self.handle_eventgui,
                        'unknown' : self.handle_unknown,
                        'exitguievent' : self.handle_exitguievent,
                        }

        self.register_gui()

    def handle_read(self):
        log.debug("Reading data on channel (%d)" % self._fileno)

        self.in_buffer = self.recv(prop.max_message_len)
        log.debug(repr(self.in_buffer))

        if self.in_buffer == '':
            return False

        remaining_msg = self.in_buffer

        while True:
            try:
                self.fields, self.data, remaining_msg = parseMessage(remaining_msg)
            except Error, e:
                #log.debug(repr(self.in_buffer))
                log.warn("Message parsing error: %s (%d)" % (e.opt, e.msg))
                self.out_buffer = self.handle_unknown()
                log.debug(self.out_buffer)
                return True

            msg_type = self.fields.get('msg', 'unknown')
            log.debug("%s %s %s" % ("*"*40, msg_type, "*"*40))
            log.debug(repr(self.in_buffer))

            try:
                self.out_buffer = self.handlers.get(msg_type, self.handle_unknown)()
            except Error:
                log.error("Unhandled exception during processing")

            if len(self.out_buffer): # data is ready for send
                self.sock_write_notifier.setEnabled(True)

            if not remaining_msg:
                break

        return True

    def handle_write(self):
        if not len(self.out_buffer):
            return

        log.debug("Sending data on channel (%d)" % self._fileno)
        log.debug(repr(self.out_buffer))
        
        try:
            sent = self.send(self.out_buffer)
        except:
            log.error("send() failed.")

        self.out_buffer = self.out_buffer[sent:]
        

    def writable(self):
        return not ((len(self.out_buffer) == 0)
                     and self.connected)

    def handle_exitguievent(self):
        self.signal_exit = True
        if self.signal_exit:
            if sendfax is not None:
                sendfax.close()
            qApp.quit()

        return ''

    # EVENT
    def handle_eventgui(self):
        if sendfax is not None:
            try:
                job_id = self.fields['job-id']
                event_code = self.fields['event-code']
                event_type = self.fields['event-type']
                retry_timeout = self.fields['retry-timeout']
                lines = self.data.splitlines()
                error_string_short, error_string_long = lines[0], lines[1]
                device_uri = self.fields['device-uri']
                printer_name = self.fields.get('printer', '')
                title = self.fields.get('title', '')
                fax_file = self.fields.get('fax-file', '')
    
                log.debug("Event: %d '%s'" % (event_code, event_type))
    
                sendfax.EventUI(event_code, event_type, error_string_short,
                                error_string_long, retry_timeout, job_id,
                                device_uri, printer_name, title, fax_file)
    
            except:
                log.exception()
    
        return ''

    def handle_unknown(self):
        #return buildResultMessage('MessageError', None, ERROR_INVALID_MSG_TYPE)
        return ''

    def handle_messageerror(self):
        return ''

    def handle_close(self):
        log.debug("closing channel (%d)" % self._fileno)
        self.connected = False
        async.dispatcher.close(self)

    def register_gui(self):
        out_buffer = buildMessage("RegisterGUIEvent", None, 
                                  {'type': 'fax', 
                                   'username': prop.username})
        self.send(out_buffer)




def usage():
    formatter = utils.usage_formatter()
    log.info(utils.bold("""\nUsage: hp-sendfax [OPTIONS]\n\n""" ))
    utils.usage_options()
    utils.usage_device(formatter)
    utils.usage_printer(formatter)
    log.info(formatter.compose(("To specify standalone mode:", "-s or --standalone")))
    log.info(formatter.compose(("To specify job mode:", "-j or --job")))
    log.info(formatter.compose(("To specify the CUPS job ID:", "-i<jobid> or --jobid=<jobid>")))
    log.info(formatter.compose(("To specify the job title:", "-t<title> or --title=<title>")))
    log.info(formatter.compose(("To specify the job username:", "-u<username> or --user=<username>")))
    utils.usage_logging(formatter)
    utils.usage_help(formatter, True)
    sys.exit(0)


def main(args):
    prop.prog = sys.argv[0]
    utils.log_title('HP SendFax', _VERSION)
    device_uri = None
    printer_name = None
    num_copies = 1
    fax_file = ''
    title = ''
    job_id = -1
    standalone = True
    username = ''
    
    try:
        opts, args = getopt.getopt(sys.argv[1:], 
            'l:hd:p:i:o:u:f:sjt:z:', 
            ['level=', 'help', 'device=', 'job', 'jobid=',
             'options=', 'user=', 'printer=',
             'file=', 'standalone', 'title=', 'logfile='])

    except getopt.GetoptError:
        usage()

    if os.getenv("HPLIP_DEBUG"):
        log.set_level('debug')
    
    
    for o, a in opts:
        if o in ('-l', '--logging'):
            log_level = a.lower().strip()
            if not log.set_level(log_level):
                usage()
                
        elif o in ('-z', '--logfile'):
            log.set_logfile(a)
            log.set_where(log.LOG_TO_CONSOLE_AND_FILE)

        elif o in ('-h', '--help'):
            usage()
            
        elif o in ('-d', '--device'):
            device_uri = a

        elif o in ('-p', '--printer'):
            printer_name = a
            
        elif o in ('-f', '--file'):
            fax_file = a
            
        elif o in ('-t', '--title'):
            title = a
            
        elif o in ('-i', '--jobid'):
            try:
                job_id = int(a)
            except ValueError:
                job_id = -1
        
        elif o in ('-s', '--standalone'):
            standalone = True
                
        elif o in ('-j', '--job'):
            standalone = False
            
        elif o in ('-u', '--user'):
            username = a
            
    
    # Security: Do *not* create files that other users can muck around with
    os.umask (0077)
    log.set_module('sendfax')

    global client
    try:
        client = fax_client()
    except Error:
        log.error("Unable to create client object.")
        sys.exit(1)

    # create the main application object
    global app
    app = QApplication(sys.argv)

    global sendfax
    sendfax = FaxSendJobForm(client.socket,
                             device_uri, 
                             printer_name, 
                             username, job_id,
                             title, fax_file, 
                             standalone)
                             
    app.setMainWidget(sendfax)

    pid = os.getpid()
    log.debug('pid=%d' % pid)

    sendfax.show()
    
    signal.signal(signal.SIGPIPE, signal.SIG_IGN)

    user_config = os.path.expanduser('~/.hplip.conf')
    loc = utils.loadTranslators(app, user_config)

    try:
        log.debug("Starting GUI loop...")
        app.exec_loop()
    except KeyboardInterrupt:
        pass
    except:
        log.exception()

    return 0

if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))
