 # ====================================================================
 # Copyright (c) 2004-2006 Open Source Applications Foundation.
 #
 # Permission is hereby granted, free of charge, to any person obtaining a
 # copy of this software and associated documentation files (the "Software"),
 # to deal in the Software without restriction, including without limitation
 # the rights to use, copy, modify, merge, publish, distribute, sublicense,
 # and/or sell copies of the Software, and to permit persons to whom the
 # Software is furnished to do so, subject to the following conditions: 
 #
 # The above copyright notice and this permission notice shall be included
 # in all copies or substantial portions of the Software. 
 #
 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 # DEALINGS IN THE SOFTWARE.
 # ====================================================================


class JavaError(Exception):
    def getJavaException(self):
        return self.args[0]


class InvalidArgsError(Exception):
    pass


from _PyLucene import *


import threading

# A few kludges here because starting the OS thread is done by libgcj
# instead of python.
    
class PythonThread(threading.Thread):
    """
    A threading.Thread extension that delegates starting of the
    actual OS thread to libgcj. In order to keep libgcj's garbage collector
    happy, any python thread using libgcj must be of this class.
    """

    def __init__(self, *args, **kwds):

        super(PythonThread, self).__init__(*args, **kwds)
        self.javaThread = None

    def start(self):

        current = threading.currentThread()
        assert (current.getName() == 'MainThread' or isinstance(current, PythonThread)), "PythonThread can only be started from main thread of from another PythonThread"
        
        class runnable(object):
            def __init__(_self, callable):
                _self.callable = callable
            def run(_self):
                try:
                    _self.callable()
                finally:
                    del _self.callable
                    self.javaThread = None

        threading._active_limbo_lock.acquire()
        threading._limbo[self] = self
        threading._active_limbo_lock.release()
        
        thread = self.javaThread = Thread(runnable(self._Thread__bootstrap),
                                          self.getName())
        thread.start()

        self._Thread__started = True

    def join(self, timeout=None):

        thread = self.javaThread
        if thread is not None:
            if timeout is not None:
                thread.join(long(timeout * 1000))
            else:
                thread.join()


def monkeypatch():
    """
    Monkey patch standard library threading module to use PythonThread.

    This function replaces Python's threading.Thread class with this
    module's PythonThread class, an extension of threading.Thread that
    delegates the actual OS thread setup to libgcj.
    """

    threading.Thread=PythonThread
    threading._Timer.__bases__=(PythonThread,)
