import json
from datetime import datetime

import pytz
import tornado

from core.prometheus_metrics_handler import api_requests_counter
from core.utils import serialize_everything


class APIStatusHandler(tornado.web.RequestHandler):
    """API request handler for /api/v1/status"""

    def initialize(self, status_data, web_server_metrics):
        self._status_data = status_data
        self._web_server_metrics = web_server_metrics

    def get(self):
        # Metrics
        self._web_server_metrics["last_api_access_time"] = datetime.now(pytz.UTC)
        self._web_server_metrics["api_access_counter"] += 1
        self._web_server_metrics["status"] = "OK"
        api_requests_counter.inc()

        self.write(json.dumps(self._status_data, default=serialize_everything))
        self.set_status(200)
        self.set_header("Cache-Control", "no-store")
        self.set_header("Content-Type", "application/json")
