import time


def check_instance_drained(ecs_c, cluster_name, instance_id, context):

    """
    Checks and waits until an ECS instance has drained all its running tasks.

    Returns True if the instance drains.

    Returns False if there is less than 40 seconds left in the Lambda
    functions execution and we need to re-invoke to wait longer.
    """

    while True:

        response = ecs_c.describe_container_instances(
            cluster=cluster_name,
            containerInstances=[
                instance_id
            ]
        )

        print("- Instance has {} running tasks and {} pending tasks".format(
            response["containerInstances"][0]["runningTasksCount"],
            response["containerInstances"][0]["pendingTasksCount"]
        ))

        if response["containerInstances"][0]["runningTasksCount"] == 0 and \
                response["containerInstances"][0]["pendingTasksCount"] == 0:
            return(True)

        if context.get_remaining_time_in_millis() <= 40000:
            return(False)

        time.sleep(30)