import datetime
import time
from logging import Logger
from typing import override

from test_automation_suite.checks.check import Check
from test_automation_suite.core.context import Context
from test_automation_suite.core.task import Step, StepResult
from test_automation_suite.utility.screenshot import is_screen_all_black
from test_automation_suite.utility.suspend import suspend


class CheckSuspends(Check):
    suspend_duration: int = 120
    suspend_tolerance: int = 5
    suspend_count: int = 3

    @override
    def steps(self) -> list[Step]:
        return [*super().steps(), self.step_run]

    def step_run(self, context: Context, logger: Logger) -> StepResult:
        timestamp = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
        screenshot_location = context.output_directory / f"check-suspend-{timestamp}.png"

        logger.info("Screenshot filename: %s", str(screenshot_location))

        if is_screen_all_black(screenshot_location):
            logger.error("Initial screenshot failed")
            return StepResult(success=False)

        for i in range(self.suspend_count):
            logger.info("Running suspend check nr %i", i + 1)

            if not suspend(self.suspend_duration, self.suspend_tolerance):
                logger.error("Suspend check nr %i failed", i + 1)
                return StepResult(success=False)

            # wait to make sure everything has properly woken up
            time.sleep(5)

            if is_screen_all_black(screenshot_location):
                logger.error("Screen was black after suspend")
                return StepResult(success=False)

        return StepResult(success=True)
