#   Copyright 2000-2004 Michael Hudson mwh@python.net
#
#                        All Rights Reserved
#
#
# Permission to use, copy, modify, and distribute this software and
# its documentation for any purpose is hereby granted without fee,
# provided that the above copyright notice appear in all copies and
# that both that copyright notice and this permission notice appear in
# supporting documentation.
#
# THE AUTHOR MICHAEL HUDSON DISCLAIMS ALL WARRANTIES WITH REGARD TO
# THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
# AND FITNESS, IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL,
# INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER
# RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
# CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
# CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

from Foundation import NSObject, NSFileHandle, NSNotificationCenter, \
     NSFileHandleDataAvailableNotification
from AppKit import NSApp
import os

# creating a thread for each keypress is probably a little excessive!

# XXX arrow keys don't quite work

class CocoaInteracter(NSObject):
    def init(self, con, inputfilehandle=None, outputfilehandle=None):
        self = NSObject.init(self)
        if inputfilehandle is None:
            inputfilehandle = NSFileHandle.fileHandleWithStandardInput()
        if outputfilehandle is None:
            outputfilehandle = NSFileHandle.fileHandleWithStandardOutput()
        self.ifh = inputfilehandle
        self.ofh = outputfilehandle
        self.con = con
        con.prepare()
        NSNotificationCenter.defaultCenter().addObserver_selector_name_object_(
            self, "handleInput:", NSFileHandleDataAvailableNotification, self.ifh) 
        self.ifh.waitForDataInBackgroundAndNotify()
        NSApp().delegate().con = self.con
        return self

    def handleInput_(self, aNotification):
        try:
            data = self.ifh.availableData()
            for c in unicode(data.bytes(), self.con.reader.console.encoding):
                self.con.reader.console.event_queue.push(c)
            while not self.con.reader.console.event_queue.empty():
                self.con.handle1(block=0)
        except EOFError:
            self.con.restore()
            print "session ends"
        else:
            self.ifh.waitForDataInBackgroundAndNotify()
            
