from isapi import isapicon
from isapi.simple import SimpleExtension
import sys, os, stat

if hasattr(sys, "isapidllhandle"):
    import win32traceutil
from django.core.handlers import d4i
from isapi import InternalReloadException
import win32event, win32file, winerror, win32con, threading
from isapi import threaded_extension



class Extension(threaded_extension.ThreadPoolExtension):
	"D4I ISAPIExtension ver 0.1.0"
	def Dispatch(self, ecb): 
		d4i.handler(ecb)

# The entry points for the ISAPI extension.
def __ExtensionFactory__():
	return Extension()

# Our special command line customization.
# Pre-install hook for our virtual directory.
def PreInstallDirectory(params, options):
    # If the user used our special '--description' option,
    # then we override our default.
    if options.description:
        params.Description = options.description

# Post install hook for our entire script
def PostInstall(params, options):
    print ""
    print "The sample has been installed."
    print "Point your browser to /AdvancedPythonSample"
    print "If you modify the source file and reload the page,"
    print "you should see the reload counter increment"

# Handler for our custom 'status' argument.
def status_handler(options, log, arg):
    "Query the status of something"
    print "Everything seems to be fine!"

custom_arg_handlers = {"status": status_handler}

if __name__=='__main__':
    # If run from the command-line, install ourselves.
    from isapi.install import *
    params = ISAPIParameters()
    # Setup the virtual directories - this is a list of directories our
    # extension uses - in this case only 1.
    # Each extension has a "script map" - this is the mapping of ISAPI
    # extensions.
    sm = [
        ScriptMapParams(Extension="*", Flags=0)
    ]
    vd = VirtualDirParameters(Name="D4I",
                              Description = Extension.__doc__,
                              ScriptMaps = sm,
                              ScriptMapUpdate = "replace",
                              # specify the pre-install hook.
                              PreInstall = PreInstallDirectory
                              )
    params.VirtualDirs = [vd]
    # Setup our custom option parser.
    from optparse import OptionParser
    parser = OptionParser('') # black usage, so isapi sets it.
    parser.add_option("", "--description",
                      action="store",
                      help="custom description to use for the virtual directory")
    
    HandleCommandLine(params, opt_parser=parser, 
                              custom_arg_handlers = custom_arg_handlers)
