'''
 ====================================================================
 Copyright (c) 2003-2006 Barry A Scott.  All rights reserved.

 This software is licensed as described in the file LICENSE.txt,
 which you should have received as part of this distribution.

 ====================================================================

    wb_shell_macosx_commands.py

'''
import os
import popen2
import xml.sax.saxutils

def getTerminalProgramList():
    return ['Terminal','iTerm']

def getFileBrowserProgramList():
    return ['Finder']

def GuiDiffFiles( app, options ):
    cmd_line = "'%s' %s &" % (app.prefs.getDiffTool().gui_diff_tool, options)
    app.log.info( cmd_line )
    os.system( cmd_line )

def ShellDiffFiles( app, options ):
    cmd_line = "'%s' %s" % (app.prefs.getDiffTool().shell_diff_tool, options)
    app.log.info( cmd_line )
    return __run_command_with_output( cmd_line )

def EditFile( app, project_info, filename ):
    p = app.prefs.getEditor()

    if p.editor_image:
        if p.editor_options:
            command_line = '"%s" %s "%s" &' % \
                (p.editor_image, p.editor_options, filename)
        else:
            command_line = '"%s" "%s" &' % \
                (p.editor_image, filename)
    else:
        command_line = '"open" -e "%s" &' % filename

    app.log.info( command_line )
    cur_dir = os.getcwd()
    try:
        os.chdir( project_info.getWorkingDir() )
        os.system( command_line )
    finally:
        os.chdir( cur_dir )

def ShellOpen( app, project_info, filename ):
    app.log.info( 'Open %s' % filename )
    cur_dir = os.getcwd()
    try:
        os.chdir( project_info.getWorkingDir() )
        os.system( 'open "%s"' % filename )
    finally:
        os.chdir( cur_dir )

def CommandShell( app, project_info ):
    p = app.prefs.getShell()
    if p.shell_terminal == 'iTerm':
        CommandShell_iTerm( app, project_info )
    else:
        CommandShell_Terminal( app, project_info )

def CommandShell_iTerm( app, project_info ):
    shell_script_filename = os.path.join( '/tmp', 'wb.scpt' )

    p = app.prefs.getShell()
    working_dir = project_info.getWorkingDir()

    # calc a title that is leaf to root so that the leaf shows up in a task bar first
    title = []
    pi = project_info
    while pi:
        title.append( pi.project_name )
        pi = pi.parent

    commands = 'cd "%s"' % working_dir

    if len( p.shell_init_command ) > 0:
        commands = commands + ';. "%s"\n' % p.shell_init_command

    f  = open( shell_script_filename, 'w' )
    f.write( '''
tell application "iTerm"
    activate 

    -- make a new terminal
    set work_bench_term to (make new terminal) 

    -- talk to the new terminal
    tell work_bench_term 
        activate current session
        launch session "Default Session"

        -- talk to the session
        tell the last session
            set name to "%s"

            -- execute a command
            exec command "/bin/bash"

            write text "%s"

        end tell

    end tell

end
''' %   (' '.join( title ).replace( '"', '\\"' )
        ,commands.replace( '"', '\\"' )) )
    f.close()

    command_line = '"osascript" "%s" &' % shell_script_filename

    app.log.info( command_line )
    os.system( command_line )

def CommandShell_Terminal( app, project_info ):
    shell_script_filename = os.path.join( '/tmp', 'wb.term' )

    p = app.prefs.getShell()
    working_dir = project_info.getWorkingDir()

    # calc a title that is leaf to root so that the leaf shows up in a task bar first
    title = []
    pi = project_info
    while pi:
        title.append( pi.project_name )
        pi = pi.parent

    commands = 'cd "%s"' % working_dir

    if len( p.shell_init_command ) > 0:
        commands = commands + ';. "%s"\n' % p.shell_init_command

    f  = open( shell_script_filename, 'w' )
    f.write( '''<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>WindowSettings</key>
    <array>
        <dict>
            <key>CustomTitle</key>
            <string>%s</string>
            <key>ExecutionString</key>
            <string>%s</string>
        </dict>
    </array>
</dict>
</plist>
''' % (xml.sax.saxutils.escape( ' '.join( title ) ), xml.sax.saxutils.escape( commands )) )
    f.close()

    command_line = '"open" "%s" &' % shell_script_filename

    app.log.info( command_line )
    os.system( command_line )

def FileBrowser( app, project_info ):
    command_line = 'open -a "Finder" "%s" &' % project_info.getWorkingDir()

    app.log.info( command_line )
    os.system( command_line )

def __run_command_with_output( command_line ):
    print 'command_line',command_line
    err_prefix = 'error running %s' % command_line
    try:
        proc = popen2.Popen3( '%s 2>&1' % command_line )
        output = proc.fromchild.read()
        rc = proc.wait()
    except EnvironmentError, e:
        return '%s - %s' % (err_prefix, str(e))

    return __run_command_with_output_error_return( err_prefix, rc, output )

def __run_command_with_output_error_return( prefix, rc, output ):
    # check for OK
    if os.WIFEXITED( rc ):
        return output

    # some error
    return '%s, rc=%d' % (prefix, rc)
