#!/usr/bin/python

# Copyright (c) 2011 Riverbank Computing Limited.
#
# This file is part of dip.
#
# This file may be used under the terms of the GNU General Public License
# v2 or v3 as published by the Free Software Foundation which can be found in
# the files LICENSE-GPL2.txt and LICENSE-GPL3.txt included in this package.
# In addition, as a special exception, Riverbank gives you certain additional
# rights.  These rights are described in the Riverbank GPL Exception, which
# can be found in the file GPL-Exception.txt in this package.
#
# This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
# WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.


import optparse
import os.path
import sys

from dip.automate import Robot


# Define a hook that will be called before the event loop is called for the
# first time.

def exec_hook():

    # Create a robot to record all the automation commands in the right
    # sequence.
    robot = Robot(delay=options.delay, timeout=options.timeout)

    for step in automation_commands:
        step.record(robot)

    robot.play(after=0)

    # Remove the hook so it is only ever called once.
    delattr(sys.modules['__builtin__'], '__pyQtPreEventLoopHook__')

setattr(sys.modules['__builtin__'], '__pyQtPreEventLoopHook__', exec_hook)


# Parse the command line.
option_parser = optparse.OptionParser(
		usage="%prog [options] application argument...")

option_parser.add_option("-c", "--commands", dest='commands', action='append',
        default=[], metavar="FILE",
        help="add the automation commands defined in FILE")
option_parser.add_option("-d", "--delay", dest='delay', type='int',
        default=200,
        help="the delay in milliseconds between automation commands "
                "[default: 200]")
option_parser.add_option("-t", "--timeout", dest='timeout', type='int',
        default=5000,
        help="the time in milliseconds to wait for a widget to become visible "
                "[default: 5000]")

options, args = option_parser.parse_args()

if len(args) == 0:
    option_parser.print_usage()
    sys.stderr.write("An application must be specified.\n")
    sys.exit(1)

# Import the automation commands.
automation_commands = []

for commands_file in options.commands:
    # Convert the pathname of the .py file to a directory on the Python path
    # and the name of a module.
    dirname, filename = os.path.split(commands_file)

    if dirname != '':
        sys.path.insert(1, dirname)

    if filename.endswith('.py'):
        filename = filename[:-3]

    # Import the module and get the automation_commands object.
    module = __import__(filename)

    automation_commands += getattr(module, 'automation_commands', [])

    if dirname != '':
        del sys.path[1]

# Run the application.
sys.argv = args

with open(args[0]) as f:
    exec(f.read())
