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

def download_to_camera_roll( urls ):
    # If we assume that the only files we are asked to download are either photos or
    # videos, we can distinguish between them by the presense of the "SAVE_TO_PHOTOS"
    # button.  Videos must be downloaded first, and moved to the camera roll in a second
    # step.
    save_to_photos_strings = get_ios_strings( "WebCore", "SAVE_TO_PHOTOS" )

    if not isinstance( urls, list ):
       urls = [urls]

    launchApplication( "com.apple.mobilesafari" )
    for url in urls:
        tap( "TabBarItemTitle" )
        typeText( url + "\n" )
        pictures = getElements( None, "image" )

        # This is just to download 1 picture, which should start toward the top of the screen
        for picture in pictures:
            if picture.y < 200: #There's an internal image at the bottom of the screen we want to ignore
                break
        else:
            raise Exception( "Could not locate image" )

        picture.center.tapAndHold()
        tap( save_to_photos_strings )

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

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

cfrun(__name__, run, add_options )
