# Copyright 2022 The Debusine Developers
# See the AUTHORS file at the top-level directory of this distribution
#
# This file is part of Debusine. It is subject to the license terms
# in the LICENSE file found in the top-level directory of this
# distribution. No part of Debusine, including this file, may be copied,
# modified, propagated, or distributed except according to the terms
# contained in the LICENSE file.
"""Debusine client controller."""

import logging

import yaml

from . import common
from .waiter import Waiter

logger = logging.getLogger(__name__)


class Client:
    """Manage debusine Client."""

    @staticmethod
    def execute_command(command, *args, stdin=None):
        """
        Execute a debusine client command.

        :return: dictionary with the YAML-parsed standard output of the command
        """
        cmd = ['debusine'] + [command] + list(map(str, args))
        result = common.run(cmd, stdin=stdin).stdout

        output = yaml.safe_load(result)

        return output

    @classmethod
    def wait_for_work_request(cls, work_request_id, field, expected):
        """Wait for a work request to have expected in field."""

        def finished():
            result = cls.execute_command('work-request-status', work_request_id)

            return result[field] == expected

        return Waiter.wait_for_success(3600, finished)
