"""
jxshortcut.py

Create a shortcut for jxconfig program on a Windows system
"""



from glob import glob
from win32com.shell import shell
import pythoncom
import os


JX_ICON_PATH =  "/whi/jx/org/wh/client/image/"
JX_ICON = JX_ICON_PATH + "FrontEndStarterImage.ICO"
JXADMIN_ICON = JX_ICON_PATH + "BackEndStarterImage.ICO"
JXCONFIG = "jxconfig.py"
JXADMIN = '/whi/jx/org/wh/bin/BackEndStarter.bat'
# wildcards for possible python path locations on windows
PYTHON_LOCATIONS = ("C:/python*", "C:/Program Files/python*", "C:/Program Files (x86)/python*")




class Shortcut:
    """
     From a demo by Mark Hammond, corrupted by Mike Fletcher (and Ron Bryant)
     """
    def __init__( self ):
        self._base = pythoncom.CoCreateInstance( shell.CLSID_ShellLink, None,
                     pythoncom.CLSCTX_INPROC_SERVER, shell.IID_IShellLink )

    def load( self, filename ):
        # Get an IPersist interface
        # which allows save/restore of object to/from files
        self._base.QueryInterface( pythoncom.IID_IPersistFile ).Load(filename)

    def save( self, filename ):
        self._base.QueryInterface( pythoncom.IID_IPersistFile ).Save(filename, 0)

    def __getattr__( self, name ):
        if name != "_base":
            return getattr( self._base, name )



def create_shortcut( shortcut_data ):
    # add full pathname of user's desktop to shortcut filenames
    linkfile = os.environ['USERPROFILE'] + '\\Desktop\\' + shortcut_data.pop(0)
    # toss the shortcut description too
    shortcut_data.pop(0)
    shortcut = Shortcut()

    data = zip( shortcut_data, ("SetPath", "SetArguments",
            "SetDescription", "SetWorkingDirectory", "SetIconLocation") )
    for value, function in data:
        if value and function:
            # call function on each non-null value
            if function == "SetIconLocation":
                getattr( shortcut, function)( value, 0 )
            else:
                getattr( shortcut, function)( value )
    shortcut.save( linkfile )



def pythonw_path( wildcards ):
    """
    Determine what the path is to 'pythonw.exe' program
    """
    for wildcard in wildcards:
        paths = glob(wildcard)
        if paths:
            #files.sort(reverse=True)
            paths.sort()
            paths.reverse()
            for path in paths:
                if os.path.isdir(path):
                    pwpath = os.path.join(path, "pythonw.exe")
                    if os.path.exists(pwpath):
                        return pwpath
    return None




if __name__ == '__main__':
    pwpath = pythonw_path(PYTHON_LOCATIONS)
    if pwpath is None:
        raise SystemExit
    shortcut_data = ['jxconfig.lnk', "JX Config", pwpath, JXCONFIG,
             "Shortcut to JXconfig", 'C:/Program Files/Amador/bin',
             JXADMIN_ICON ]
    create_shortcut( shortcut_data )
