find_element() {
    local locator="$1"
    local location=$(
        adb shell "uiautomator dump && cat /sdcard/window_dump.xml" |
            awk 'BEGIN{RS=">"}1' |
            awk -v locator=$locator 'match($0, locator)'
    )
    if [ -z "$location" ]; then
        return 1
    else
        echo "$location"
    fi
}

wait_for() {
    local timeout
    timeout=${timeout:=5}

    local locator="$1"
    local location
    for i in $(seq 1 $timeout); do
        location=$(find_element "$locator")
        [ -n "$location" ] && break
    done
    if [ -z "$location" ]; then
        return 1
    else
        return 0
    fi
}

get_location() {
    find_element "$@" |
        awk -F '\\[|\\]|,' '{print ($(NF-5)+$(NF-2))/2, ($(NF-4)+ $(NF-1))/2}'
}
get_text() {
    find_element "$1" |
        sed -E -n 's#.*text="([^"]*)".*#\1#p'
}

#todo
get_attribute() {
    local key=${key:=$1}
    find_element "$1" |
        sed -E -n 's#.*text="([^"]*)".*#\1#p'
}

#
click() {
    for p in "$@"; do
        local location=$(get_location "$p" | head -1)
        [ -z "$location" ] && {
            echo "$p not found"
            break
        }
        adb shell input tap $location </dev/null
    done
}

#受限于输入法，只能输入数字与字母，中文需要使用appium的输入法
text() {
    adb shell input text "$@"
}
back() {
    adb shell input keyevent 4
}

