#!/usr/bin/env python

# This smoke test
# 1. launches the dialer with launch_app
# 2. verifies it has launched correctly
# 3. closes the dialer with aul_test term_pid

import fmbttizen
import os
import time
import sys

# Command for logging into IVI device.
# If not running in CI (the CI_SSH environment variable is not set),
# assume that "ssh root@ivi" gives the shell. (You'll need the keys!)
ssh = os.getenv("CI_SSH", "ssh root@ivi")

print "using ssh:", ssh

def dialers_pid(dut):
    "Return the PID of the dialer application"
    s, o, e = dut.shellSOE("aul_test getallpkg all")
    dialer_index = o.find("org.tizen.dialer")
    assert dialer_index > 0, "cannot see dialer in 'aul_test getallpkg all' output"
    pid_index = o.find("pid: ", dialer_index)
    assert pid_index > 0, "cannot see dialer pid in 'aul_test getallpkg all' output"
    pid = int(o[pid_index + len("pid: "):].split()[0])
    return pid

if __name__ == "__main__":
    # The test starts here
    dut = fmbttizen.Device(loginCommand=ssh)
    dut.enableVisualLog("device.html")
    dut.setBitmapPath(os.path.dirname(os.path.realpath(__file__)))
    dut.refreshScreenshot()

    # Check that dialer is not already running. If it is,
    # consider this test passed and do nothing else.
    if dut.verifyBitmap("bitmaps/dialer-dial.png"):
        sys.exit(0)

    # Launch dialer and verify it becomes visible on the display.
    s, o, e = dut.shellSOE("launch_app org.tizen.dialer")
    assert s == 0, "launch_app: non-zero exit status"
    time.sleep(3.0)
    dut.refreshScreenshot()
    assert dut.waitBitmap("bitmaps/dialer-dial.png"), "cannot see dialer-dial.png"

    # Find dialer's PID.
    pid = dialers_pid(dut)
    dut.visualLog("terminating pid: %s" % (pid,))

    # Terminate dialer with aul_test term_pid <pid>
    # and verify that it disappeared.
    dut.shellSOE("aul_test term_pid %s" % (pid,))
    time.sleep(1.0)
    dut.refreshScreenshot()
    assert dut.verifyBitmap("bitmaps/dialer-dial.png") == False, "dialer not terminated"
