"""UISP Integration"""
import json
from . import HttpClient


class UnmsApiClient(HttpClient):
    """Query the uNMS API."""

    def __init__(self, url, api_token, verbose=0):
        super().__init__(url + '/v2.1', verify_ssl=False)
        self._hdr = {'X-Auth-Token': api_token}
        self.verbose = verbose

    async def query(self, path):
        """Make a GET request to an API endpoint."""
        r = await self.request(path, headers=self._hdr)
        if self.verbose > 2:
            print(f'uNMS Request: {path}')
            if self.verbose > 2:
                print(json.dumps(r, indent=2))
        return r

    async def authenticate(self):
        """Do a simple query to check authentication."""
        await self.get_nms_version()

    async def get_sites(self):
        return await self.query('/sites')

    async def get_devices(self, site_id=None):
        params = '?siteId={}'.format(site_id) if site_id else ''
        return await self.query('/devices{}'.format(params))

    async def get_device_interfaces(self, device_id):
        return await self.query(f'/devices/{device_id}/interfaces')

    async def get_nms_settings(self):
        return await self.query('/nms/settings')

    async def get_nms_version(self):
        data = await self.query('/nms/version')
        if data and isinstance(data, dict):
            return data.get('version')
        raise RuntimeError(f'Failed to get NMS version: {data}')

    async def get_credentials(self, device_id):
        """Get credentials for a device from the UISP Vault.  Requires admin token."""
        return await self.query(f'/vault/{device_id}/credentials')
