import logging
import time

from test_automation_suite.utility.cmd import run_cmd_t

logger = logging.getLogger(__name__)


def suspend(sleep_time: int = 120, tolerance: int = 5) -> bool:
    logger.info("System going to sleep for %d sec zzZ", sleep_time)
    start_time = time.time()

    cmd: str = f"sudo rtcwake -m mem -s {sleep_time}"
    _result, error = run_cmd_t(cmd)
    if error:
        logger.error("I can't sleep because of: %s", error)
        return False

    end_time = time.time()
    actual_sleep = end_time - start_time
    logger.info("System woke up from sleep, slept for %.1f sec", actual_sleep)

    if actual_sleep + tolerance >= sleep_time:
        return True
    logger.warning("Suspend was too short: %.1f sec < %d sec", actual_sleep, sleep_time)
    return False
