from datetime import datetime
from typing import Any

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

from core.config import ALLOW_SPOTTING, WEB_UI_OPTIONS, BASE_URL, SERVER_OWNER_CALLSIGN
from core.constants import SOFTWARE_VERSION
from core.prometheus_metrics_handler import page_requests_counter


class PageTemplateHandler(tornado.web.RequestHandler):
    """Handler for all HTML pages generated from templates"""

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

    def initialize(self, template_name, web_server_metrics):
        self._template_name = template_name
        self._web_server_metrics = web_server_metrics

    def get(self):
        # Metrics
        self._web_server_metrics["last_page_access_time"] = datetime.now(pytz.UTC)
        self._web_server_metrics["page_access_counter"] += 1
        self._web_server_metrics["status"] = "OK"
        page_requests_counter.inc()

        # Load named template, and provide variables used in templates
        self.render(self._template_name + ".html", software_version=SOFTWARE_VERSION,
                    server_owner_callsign=SERVER_OWNER_CALLSIGN, allow_spotting=ALLOW_SPOTTING,
                    web_ui_options=WEB_UI_OPTIONS, baseurl=BASE_URL, current_path=self.request.path)
