import subprocess
import time

from lib_python import execution, logger, steps

__PATH_CRASH_FILE = "/data/data/com.avg.zaap.crash/files/offline/{0}.bp"
__PATH_CRASH_METADATA_FILE = "/data/data/com.avg.zaap.crash/files/offline/{0}.metadata"
__RESPONSE_OK = "0\r\r\n"


def check_that_offline_file_with_metadata_exists(params):
    timeout = 10 * 60  # 10 minutes in seconds
    start = time.time()

    file_name = params["file_name"]

    error_cause = None

    while time.time() - start < timeout:
        crash_file_path = __PATH_CRASH_FILE.format(file_name)
        response = subprocess.check_output("adb shell test -f {0}; echo $?".format(crash_file_path), shell=True)

        if not response.endswith(__RESPONSE_OK):
            error_cause = "ADB shell command did not respond with {0}".format(__RESPONSE_OK)
            logger.error(error_cause)
            continue
        else:
            # noinspection PyUnusedLocal
            error_cause = None

        metadata_file_path = __PATH_CRASH_FILE.format(file_name)
        response = subprocess.check_output("adb shell test -f {0}; echo $?".format(metadata_file_path), shell=True)

        if not response.endswith(__RESPONSE_OK):
            error_cause = "ADB shell command did not respond with {0}, response: {1}".format(__RESPONSE_OK, response)
            logger.error(error_cause)
            continue
        else:
            error_cause = None
            break

    if error_cause is not None:
        logger.error()
        execution.error(error_cause)

    execution.passed()


steps.new_step("Offline - Check that offline file {file_name} exists", check_that_offline_file_with_metadata_exists)
