#!/usr/bin/env python3
from controlfloor import *
import os

# Example app with some utilities for testing
# example:
#    # Tap 'home' button
#    python3 -m controlfloor.cmd --home
#

def open_url( url ):
    launchApplication( "com.apple.mobilesafari" )
    wait(4)
    retries = 4
    while retries:
        retries -= 1
        tap( "TabBarItemTitle" )
        wait(1)
        if not getKeyboards():
            continue
        # If the URL was empty, this button is not present
        tap( "ClearTextButton", allow_errors = True )
        break
        wait(1)

    typeText( url + "\n" )

def add_options( parser ):
    parser.add_argument( "--home",               action="store_true", help="Tap the 'home' button" )
    parser.add_argument( "--clock",              action="store_true", help="Launch the 'clock' app (com.apple.mobiletimer)" )
    parser.add_argument( "--openURL",                                 help="Open the specified URL using the device's default handler" )
    parser.add_argument( "--downloadMedia",                           help="URL to download to Camera Roll. [--filename] [--size]" )
    parser.add_argument( "--getFilenameForURL",                       help="Check URL filename..." )
    parser.add_argument( "--getScreenshot",                           help="Save screenshot using the specified filename" )
    parser.add_argument( "--getFullResolutionScreenshot",             help="Save screenshot using the specified filename" )
    parser.add_argument( "--jpegQuality",      default=0, type=int )
    parser.add_argument( "--jpegMaxDimension", default=0, type=int )
    parser.add_argument( "--jpegMaxWidth",     default=0, type=int )
    parser.add_argument( "--jpegMaxHeight",    default=0, type=int )
    parser.add_argument( "--jpegMaxScale",     default=0, type=float )
    parser.add_argument( "--filename", default="" )
    parser.add_argument( "--size", default=0, type=int )

def run( opts ):
    if opts.home:
        home()
    elif opts.clock:
        launchApplication("com.apple.mobiletimer")
    elif opts.openURL:
        openURL( opts.openURL )
    elif opts.getFilenameForURL:
        print( repr( getFilenameForURL( opts.getFilenameForURL )._ ) )
    elif opts.getScreenshot or opts.getFullResolutionScreenshot:
        path = opts.getScreenshot or opts.getFullResolutionScreenshot
        if os.path.exists(path):
            raise Exception( "File exists" )
            return
        if opts.getScreenshot:
            result = getScreenshot(maxScale=opts.jpegMaxScale, maxDimension=opts.jpegMaxDimension, jpegQuality=opts.jpegQuality, maxWidth=opts.jpegMaxWidth, maxHeight=opts.jpegMaxHeight)
        else:
            result = getFullResolutionScreenshot(maxScale=opts.jpegMaxScale, maxDimension=opts.jpegMaxDimension, jpegQuality=opts.jpegQuality, maxWidth=opts.jpegMaxWidth, maxHeight=opts.jpegMaxHeight)
        if result.error:
            raise Exception( result.error )
        if not result.binaryData:
            raise Exception( "getScreenshot() did not return binary data" )
        with open(path, 'wb') as file:
            file.write(result.binaryData)
    elif opts.downloadMedia:
        transfer = startMediaDownload( opts.downloadMedia, filename=opts.filename, size=opts.size )
        def progress(msg):
            print(repr(msg._))
        transfer.progress = progress
        waitForTransfer( transfer )
    else:
        print( "No command specified" )

cfrun(__name__, run, add_options )
