import logging
import time

from ipware import get_client_ip
from user_agents import parse

from blog.documents import ELASTICSEARCH_ENABLED, ElaspedTimeDocumentManager

logger = logging.getLogger(__name__)


#zhq: 在线中间件类 - 用于监控页面加载时间和用户访问信息
class OnlineMiddleware(object):
    def __init__(self, get_response=None):
        self.get_response = get_response
        super().__init__()

    def __call__(self, request):
        ''' page render time '''
        # zhq: 记录请求开始时间
        start_time = time.time()
        response = self.get_response(request)
        #zhq: 获取客户端IP地址和User-Agent信息
        http_user_agent = request.META.get('HTTP_USER_AGENT', '')
        ip, _ = get_client_ip(request)
        user_agent = parse(http_user_agent)
        if not response.streaming:
            try:
                #zhq: 计算页面渲染时间
                cast_time = time.time() - start_time
                # zhq: 如果启用了Elasticsearch，记录性能数据
                if ELASTICSEARCH_ENABLED:
                    time_taken = round((cast_time) * 1000, 2) #zhq: 转换为毫秒并保留2位小数
                    url = request.path
                    from django.utils import timezone
                    ElaspedTimeDocumentManager.create(
                        url=url,
                        time_taken=time_taken,
                        log_datetime=timezone.now(),
                        useragent=user_agent,
                        ip=ip)
                    # zhq: 在响应内容中替换加载时间占位符
                response.content = response.content.replace(
                    b'<!!LOAD_TIMES!!>', str.encode(str(cast_time)[:5])) #zhq: 保留前5位字符
            except Exception as e:
                logger.error("Error OnlineMiddleware: %s" % e)

        return response
