import maya.cmds as cmds

def which (program):
    '''
    If application is found, returns path.
    This works with both full application paths, and applications available
    within the OS's defined PATH
    '''
    import os
    def is_exe (fpath):
        return os.path.isfile(fpath) and os.access(fpath, os.X_OK)

    fpath, fname = os.path.split(program)
    if fpath:
        if is_exe(program):
            return program
    else:
        for path in os.environ["PATH"].split(os.pathsep):
            path = path.strip('"')
            exe_file = os.path.join(path, program)
            if is_exe(exe_file):
                return exe_file

    return None


def getOSPaths ():
    import os
    paths = []
    for path in os.environ["PATH"].split(os.pathsep):
        paths.append(path.strip('"'))
    return paths


def getPythonPaths ():
    import sys
    paths = []
    for pythonPath in sys.path:
        paths.append(pythonPath)
    return paths


def getUserPaths ():
    upaths = {}
    upaths['userAppDir']         = cmds.internalVar(userAppDir=1)
    upaths['userScriptDir']      = cmds.internalVar(userScriptDir=1)
    upaths['userPrefDir']        = cmds.internalVar(userPrefDir=1)
    upaths['userPresetsDir']     = cmds.internalVar(userPresetsDir=1)
    upaths['userShelfDir']       = cmds.internalVar(userShelfDir=1)
    upaths['userMarkingMenuDir'] = cmds.internalVar(userMarkingMenuDir=1)
    upaths['userBitmapsDir']     = cmds.internalVar(userBitmapsDir=1)
    upaths['userTmpDir']         = cmds.internalVar(userTmpDir=1)
    upaths['userWorkspaceDir']   = cmds.internalVar(userWorkspaceDir=1)
    return upaths


def getEnvPaths():
    import os
    import sys
    import maya.mel as mel

    scriptPaths = mel.eval("getenv \"MAYA_SCRIPT_PATH\"")
    plugInPaths = mel.eval("getenv \"MAYA_PLUG_IN_PATH\"")
    pythonPaths = mel.eval("getenv \"PYTHONPATH\"")
    iconPaths = mel.eval("getenv \"XBMLANGPATH\"")
    pathPaths = mel.eval("getenv \"PATH\"")
    sysPaths = sys.path

    return {
        'MAYA_SCRIPT_PATH' : scriptPaths.split(os.pathsep),
        'MAYA_PLUG_IN_PATH' : plugInPaths.split(os.pathsep),
        'PYTHONPATH' : pythonPaths.split(os.pathsep),
        'XBMLANGPATH' : iconPaths.split(os.pathsep),
        'PATH' : pathPaths.split(os.pathsep),
        'sys' : sysPaths
    }


def getCurrentFilePath ():
    return cmds.file(query=True, sceneName=True)


def crashRecoverDialog ():
    dirpath = cmds.internalVar(userTmpDir=1)
    mask = dirpath+'*.ma'
    filepath = cmds.fileDialog(title='Recover Crash File...', directoryMask=mask)
    if filepath is not '':
        cmds.file(filepath, open=True)
        cmds.file(renameToSave=True)

