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

def load_clipboard( text, kill_app_when_complete = False, validate = True ):
    select_all_strings  = get_ios_strings("UIKit", "SELECT_ALL")
    cut_strings         = get_ios_strings("UIKit", "CUT")
    paste_strings       = get_ios_strings("UIKit", "PASTE")

    if not text:
        raise Exception("load_clipboard called with blank text.")

    launchApplication("com.dryark.CFAUIInspector")
    wait(2)

    tap("buttonClear")
    wait(1)
    tap("buttonDismissKeyboard")
    wait(0.5)
    textViewDefault = getElements("textViewDefault")[0]
    textViewDefault.center.tap()
    wait(1)
    typeText(text)
    wait(2)

    v = getElement("textViewDefault").value
    # \u200e is the right-to-left marker used when typing Arabic,etc. in a right-to-left context,
    # iOS will insert this when pasting text, even if it was not present in the original text.
    if v.replace("\u200e","") != text.replace("\u200e",""):
        raise Exception("typeText() failed to paste all text.\nExpected: %s\nPasted:%s" %(text, v))

    # Tap & hold -> popup is not a super-reliable operation, especially on older iOS versions
    retries = 4
    while retries:
        retries -= 1
        # This seems a bit more realiable if we unfocus the text first...
        # It will also dismiss any popup menus that might be displayed so we
        # can cleanly retry
        tap("buttonDismissKeyboard")
        wait(0.5)
        textViewDefault.center.tap(duration=2) #An extremely long hold gives time for the keyboard to pop up...
        wait(1) # Time for the keyboard to display, and copy/paste option to appear
        els = getNamedElements(None, "menuItem")
        select_all = els.all(select_all_strings)
        if not select_all:
            #If we're unlucky, we might just select 1 word at the center of the screen, or even just set the cursor
            textViewDefault.center.tap(duration=2)
            wait(1)
            els = getNamedElements(None, "menuItem")
            select_all = els.all(select_all_strings)
        if not select_all:
            textViewDefault.point(0.95,0.90).tap(duration=2)
            wait(1)
            els = getNamedElements(None, "menuItem")
            select_all = els.all(select_all_strings)
            if not select_all:
                textViewDefault.point(0.95,0.90).tap()
                wait(1)
                els = getNamedElements(None, "menuItem")
                select_all = els.all(select_all_strings)
                if not select_all:
                    continue

        select_all[0].center.tap()
        wait(0.5)
        els = getNamedElements(None, "menuItem")
        cut = els.all(cut_strings)
        if not cut:
            continue
        cut[0].center.tap()
        break
    else:
        raise Exception("Failed to find copy/paste menu...")

    if validate:
        # Should already be empty if we cut all text, but just to be safe...
        tap("buttonClear")
        wait(1)
        # tap&hold is more reliable when the field is empty
        textViewDefault.center.tap(duration=2)
        wait(1)

        tap(paste_strings, "menuItem")
        wait(1)
        v = getElement("textViewDefault").value
        # \u200e is the right-to-left marker used when typing Arabic,etc. in a right-to-left context,
        # iOS will insert this when pasting text, even if it was not present in the original text.
        if v.replace("\u200e","") != text.replace("\u200e",""):
            raise Exception("Pasted text did not match copied text...\nCopied:%s\nPasted:%s" %(text, v) )

    if kill_app_when_complete:
        killApplication("com.dryark.CFAUIInspector")
    else:
        tap("buttonClear")
    wait(0.5)

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

def run( opts ):
    load_clipboard( " ".join(opts.text) )

cfrun(__name__, run, add_options )
