# Copyright 2024 The Android Open Source Project
#
# Licensed 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.
"""Utility functions to manage and interact with devices for ITS."""

import logging
import os
import subprocess

ITS_TEST_ACTIVITY = 'com.android.cts.verifier/.camera.its.ItsTestActivity'
SYSTEM_USER = '0'


def run(cmd):
  """Replacement for os.system, with hiding of stdout+stderr messages.

  Args:
    cmd: Command to be executed in string format.
  """
  with open(os.devnull, 'wb') as devnull:
    subprocess.check_call(cmd.split(), stdout=devnull, stderr=subprocess.STDOUT)


def run_adb_shell_command(device_id, command):
  """Run adb shell command on device.

  Args:
    device_id: serial id of device.
    command: adb command to run on device.
  Returns:
    output: adb command output
  Raises:
    RuntimeError: An error when running adb command.
  """
  adb_command = f'adb -s {device_id} shell {command}'
  output = subprocess.run(adb_command, capture_output=True, shell=True,
                          check=False)
  if 'Exception occurred' in str(output):
    raise RuntimeError(output)
  return output


def is_dut_tablet_or_desktop(device_id):
  """Checks if the dut is tablet or desktop.

  Args:
    device_id: serial id of device under test
  Returns:
    True, if the device under test is a tablet.
    False otherwise.
  """
  adb_command = 'getprop ro.build.characteristics'
  output = run_adb_shell_command(device_id, adb_command)
  logging.debug('adb command output: %s', output)
  if output is not None and (
      ('tablet' in str(output).lower()) or
      ('desktop' in str(output).lower())
  ):
    logging.debug('Device under test is a tablet/desktop.')
    return True
  logging.debug('Device under test is a phone')
  return False


def start_its_test_activity(device_id):
  """Starts ItsTestActivity, waking the device if necessary.

  Args:
    device_id: str; ID of the device.
  """
  run(f'adb -s {device_id} shell input keyevent KEYCODE_WAKEUP')
  run(f'adb -s {device_id} shell input keyevent KEYCODE_MENU')
  run(f'adb -s {device_id} shell am start -n '
      f'{ITS_TEST_ACTIVITY} --activity-brought-to-front '
      '--activity-reorder-to-front')


def get_current_user(device_id):
  """Returns the current user on the device."""
  adb_command = 'am get-current-user'
  output = run_adb_shell_command(
      device_id, adb_command).stdout.decode('utf-8').strip()
  logging.debug('Current user: %s', output)
  return output
