import asyncio
import logging
from typing import List

from .common import AbstractMetricCollector
from .gc_metrics import PythonGcMetricsCollector, PythonGcObjectMetricsCollector
from .system_metrics import SystemMetricsMonitor

logger = logging.getLogger(__name__)


class MetricsScheduleMonitor:
    """
    定时收集指标
    """

    def __init__(self):
        self.collectors: List[AbstractMetricCollector] = []

    def add(self, collector: AbstractMetricCollector) -> "MetricsScheduleMonitor":
        self.collectors.append(collector)
        return self

    def register_default_collectors(self) -> "MetricsScheduleMonitor":
        """
        注册默认指标收集器
        """
        self.add(SystemMetricsMonitor(interval_sec=30).register_default_collectors())
        self.add(PythonGcMetricsCollector(interval_sec=30))
        self.add(PythonGcObjectMetricsCollector(interval_sec=5))
        return self

    async def run_monitor(self):
        """运行监控任务"""

        if len(self.collectors) == 0:
            self.register_default_collectors()

        logger.info(
            f"Start system metrics monitor, collector num = {len(self.collectors)}"
        )

        async def schedule_collect(collector: AbstractMetricCollector):
            """定时收集指标数据"""
            while True:
                await collector.collect()
                await asyncio.sleep(collector.collect_interval)

        for c in self.collectors:
            asyncio.create_task(schedule_collect(c))
