import os

BASE_DIR = os.path.dirname(os.path.realpath(__file__))


def generate_client_metrics_mixin():
    print('Generating "mavtel_client.client.mixins.metrics_mixin"...')

    from mavtel_models.supported_metrics import get_supported_metrics

    supported_metrics = get_supported_metrics()

    output = '''from typing import Optional
    
from mavtel_models.mavlink.metrics import *
    
    
class MetricsMixin:
    """
    This is an autogenerated class!
    """
    '''

    for metric_name, metric_class in supported_metrics.items():
        metric_class_name = metric_class.__name__

        output += f"""
    async def {metric_name}(self) -> Optional[{metric_class_name}]:
        # noinspection PyUnresolvedReferences
        return await self.get_metric_by_class({metric_class_name})
        """

    with open(os.path.join(BASE_DIR, 'client', 'mixins', 'metrics_mixin.py'), mode='wt') as fs:
        fs.write(output)


def generate_client_mixins_services_mixin():
    print('Generating "mavtel_client.client.mixins.services_mixin"...')

    services = dict(
        session='SessionState',
        collector='CollectorState',
        storage='StorageState',
    )

    output = f'''import httpx

from mavtel_models import {", ".join(services.values())}
    
    
class ServicesMixin:
    """
    This is an autogenerated class!
    """
    '''

    for service_name, service_state_class in services.items():
        output += f"""
    async def {service_name}(self) -> {service_state_class}:
        # noinspection PyUnresolvedReferences
        url = self._api_url + '/services/{service_name}'
        async with httpx.AsyncClient() as client:
            response: httpx.Response = await client.get(url)
            return {service_state_class}(**response.json())
        """

    with open(os.path.join(BASE_DIR, 'client', 'mixins', 'services_mixin.py'), mode='wt') as fs:
        fs.write(output)


if __name__ == "__main__":
    generate_client_metrics_mixin()
    generate_client_mixins_services_mixin()
