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

def download_files( urls, wait_time = 3 ):
    if wait_time < 0:
        wait_time = 0

    # Buttom menu "Save to Files" option after tapping the "Share" button
    save_to_files_strings = get_ios_strings( "DocumentManager", "SAVE_TO_FILES" )
    # Top-right corner "save" in the "Save to Files" dialog
    save_strings          = get_ios_strings( "DocumentManager", "SAVE" )
    downloads_strings     = get_ios_strings( "DocumentManager", "DOWNLOADS" )

    # Accept a single URL or a list of URLs
    if not isinstance( urls, list ):
       urls = [urls]

    # TODO: on some versions of iOS, iOS loses access to the keyboard when killing/launching this way.
    # Should consider switching to launching via home screen icon, and avoid killing at all...
    launchApplication( "com.apple.mobilesafari" )
    wait(4)
    killApplication( "com.apple.mobilesafari", allow_errors=True )
    wait(4)
    launchApplication( "com.apple.mobilesafari" )
    wait(4)

    for url in urls:
        # Highlight the URL Bar
        tap( "TabBarItemTitle" )

        wait(1)

        #elements = getElements("ClearTextButton", "button")
        #if elements:
        #    elements[0].tap()
        #    wait(2)

        typeText( url + "\n" )

        wait(8)
        buttons = getNamedElements("Download","button", containsElementAtCenter=1)
        if buttons:
            print ("Found download button")
            buttons[0].tap()
            print ("Tapped download button" + repr(buttons[0]))
            wait(4)
            print ("Waited")
            wait(30) #download time...
            continue

        # Give a bit of time to download/load document
        wait( wait_time )
        # Not sure how to determine when a download is complete...
        # Note: you can "save" a file whose download is in progress just fine.
        # If you switch over to the file browser, the file will display with
        # an "x%" note under the file name until the download is complete.

        tap( "ShareButton" )
        wait(1)
        elements = getElements( save_to_files_strings )
        if not elements:
            print("Dark Arts...")
            # Begin dark arts...
            # Safari actually invokes the operating-system wide sharing service, which is kind-of-sort-of integrated
            # into the application structure, but also sometimes completely invisible...
            el = getElementAtPoint(150,500) #Just anywhere toward the bottom of the page where the slide-up should be
            if el.processId:
                #processes = getProcessList() #TODO: add api call
                processes = send_message("getProcessList")
                #TODO: decide whether to call this field 'pid' or processId in the API and be done with it
                for p in processes._:
                    if p.Pid == el.processId and p.Name == "SharingUIService":
                        bundleId = "com.apple.SharingUIService"
                        # You aren't ever supposed to do this yourself
                        print("Manually setting active app to %s:%d" % (bundleId,el.processId))
                        updateApplication(bundleId=bundleId, processId=el.processId)
                        elements = getElements( save_to_files_strings )
                        if not elements: #Still failed
                            backgroundApplication(bundleId=bundleId, processId=el.processId)
                        else:
                            tap( save_to_files_strings )
                            backgroundApplication(bundleId=bundleId, processId=el.processId)
                        break
        else:
            # Rely on XCTest to scroll down the bottom menu to "Save to Files"
            tap( save_to_files_strings )

        if not elements:
            raise Exception("Couldn't find option to save file. Is your URL correct?\r\n" + url + "\n" + repr(save_to_files_strings) )


        # On some iOS version, after downloading a few files, it defaults to the parent directory of the "Downloads" folder,
        # for 'reasons', I assume...
        elements = getElements(downloads_strings,"cell")
        if elements:
            elements[0].point(0.5,0.2).tap() # Doesn't respond to tap if you tap the label (too low in the cell)
            wait(3)

        # Note: initially wrote code to specify a different filename in the download
        # At least on iOS17, it looks like you can edit the file name, but this has no effect.
        # The file will always save as basename(URL) + automatically-determined-extension.
        #if filename:
        #    # A bit hacky.  There is one textfield on the snapshotted page triggered by maxDepth,
        #    # but two on a standard XCUIElement search (the other being the hidden URL textfield
        #    # underneath the save dialog).
        #    tap( None, "textField", maxDepth = 999 )
        #    typeText( filename + "\n" )
        wait(5) #TODO: check for success.  "Save" button may be greyed out for a period of time and be nonresponsive...
        # Top-right corner "save" button
        tap( save_strings )
        wait(1)

    popDelay()
    home()

def add_options( parser ):
    parser.add_argument( "--urls", nargs="+", help="URLS to download" )

def run( opts ):
    download_files( opts.urls )

cfrun(__name__, run, add_options )
