# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
# 
# http://www.apache.org/licenses/LICENSE-2.0
# 
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.

#!/bin/bash


PROJECT_PATH=$( cd "$( dirname "$0" )/.." && pwd )

function check_devices {
# FIXME
    local devices=`adb devices | awk '/List of devices attached/ { while(getline > 0) { print }}' | grep device`
    if [ -z "$devices"  ] ; then
        echo "1"
    else
        echo "0"
    fi
}

function emulate {
    declare -a avd_list=($(android list avd | grep "Name:" | cut -f 2 -d ":" | xargs))
    # we need to start adb-server
    adb start-server 1>/dev/null

    # Do not launch an emulator if there is already one running or if a device is attached
    if [ $(check_devices) == 0 ] ; then
        return
    fi

    local avd_id="1000" #FIXME: hopefully user does not have 1000 AVDs
    # User has no AVDs
    if [ ${#avd_list[@]} == 0 ]
    then
        echo "You don't have any Android Virtual Devices. Please create at least one AVD."
        echo "android"
    fi
    # User has only one AVD
    if [ ${#avd_list[@]} == 1 ]
    then
        emulator -cpu-delay 0 -no-boot-anim -cache /tmp/cache -avd ${avd_list[0]} 1> /dev/null 2>&1 &
    # User has more than 1 AVD
    elif [ ${#avd_list[@]} -gt 1 ]
    then
        while [ -z ${avd_list[$avd_id]} ]
        do
            echo "Choose from one of the following Android Virtual Devices [0 to $((${#avd_list[@]}-1))]:"
            for(( i = 0 ; i < ${#avd_list[@]} ; i++ ))
            do
                echo "$i) ${avd_list[$i]}"
            done
            read -t 5 -p "> " avd_id
            # default value if input timeout
            if [ $avd_id -eq 1000 ] ; then avd_id=0 ; fi
        done
        emulator -cpu-delay 0 -no-boot-anim -cache /tmp/cache -avd ${avd_list[$avd_id]} 1> /dev/null 2>&1 &
    fi
    
}

function clean {
    ant clean
}
# has to be used independently and not in conjunction with other commands
function log {
    adb logcat
}

function run {
    clean && emulate && wait_for_device && install && launch 
}

function install {
    
    declare -a devices=($(adb devices | awk '/List of devices attached/ { while(getline > 0) { print }}' | grep device | cut -f 1))
    local device_id="1000" #FIXME: hopefully user does not have 1000 AVDs
    
    if [ ${#devices[@]} == 0 ]
    then
        # should not reach here. Emulator should launch or device should be attached
        echo "Emulator not running or device not attached. Could not install debug package"
        exit 70
    fi
    
    if [ ${#devices[@]} == 1 ]
    then
        export ANDROID_SERIAL=${devices[0]}
    # User has more than 1 AVD
    elif [ ${#devices[@]} -gt 1 ]
    then
        while [ -z ${devices[$device_id]} ]
        do
            echo "Choose from one of the following devices/emulators [0 to $((${#devices[@]}-1))]:"
            for(( i = 0 ; i < ${#devices[@]} ; i++ ))
            do
                echo "$i) ${devices[$i]}"
            done
            read -t 5 -p "> " device_id
            # default value if input timeout
            if [ $device_id -eq 1000 ] ; then device_id=0 ; fi
        done
        export ANDROID_SERIAL=${devices[$device_id]}
    fi

    ant debug install
}

function build {
    ant debug
}

function release {
    ant release
}

function wait_for_device {
    local i="0"
    echo -n "Waiting for device..."

    while [ $i -lt 300 ]
    do
        if [ $(check_devices) -eq 0 ]
        then
            break
        else
            sleep 1
            i=$[i+1]
            echo -n "."
        fi
    done
    # Device timeout: emulator has not started in time or device not attached
    if [ $i -eq 300 ]
    then
        echo "device timeout!"
        exit 69
    else
        echo "connected!"
    fi
}

function launch {
    local launch_str=$(java -jar "$PROJECT_PATH"/cordova/appinfo.jar "$PROJECT_PATH"/AndroidManifest.xml)
    adb shell am start -n $launch_str 
}

# TODO parse arguments
(cd "$PROJECT_PATH" && $1)
