from datetime import datetime
from typing import Any

import pytz
import tornado
from tornado import httputil
from tornado.web import Application

from core.prometheus_metrics_handler import api_requests_counter


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

    def __init__(self, application: "Application", request: httputil.HTTPServerRequest, **kwargs: Any):
        self._solar_conditions = None
        self._web_server_metrics = None
        super().__init__(application, request, **kwargs)

    def initialize(self, solar_conditions, web_server_metrics):
        self._solar_conditions = solar_conditions
        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(self._solar_conditions.to_json())
        self.set_status(200)
        self.set_header("Cache-Control", "no-store")
        self.set_header("Content-Type", "application/json")
