from flask import Response
from flask_restful import Resource

from task.dao import TaskDao
from server_status import ServerStatus, ServerStatusStore


class HealthCheckResource(Resource):
    """REST resource for health checking interface"""

    def __init__(self):
        """Health check resource constructor"""
        super().__init__()
        self.__task_dao = TaskDao.get_instance()
        self.__status_store = ServerStatusStore()

    def get(self):
        """Handles GET health check request

        Returns:
            Response: Returns with health check result.
                      200 if there is no erroneous task, 500 otherwise.
        """
        if self.__status_store.status != ServerStatus.OK:
            return Response(status=500, response=self.__status_store.message)

        for task_id in self.__task_dao.get_task_ids():
            task = self.__task_dao.get_task(task_id)
            if task.state == "error":
                return Response(status=500, response="{task_id} is in error state")
        return Response(status=200)
