import json
import logging
import requests

from pagerduty_api import log_it
from pagerduty_api.abstract_client import AbstractClient
from typing import Any, Dict


class PagerDutyTagsClient(AbstractClient):
    def __init__(
        self,
        http_session: requests.Session = requests.Session(),
        endpoint: str = 'https://api.pagerduty.com',
        auth_token: str = None,
        logger: logging.Logger = None
    ):
        super().__init__(http_session, endpoint, auth_token, logger)
        self._default_url = f'{self._endpoint}/tags'
        self._default_entity_name = 'tags'

    @log_it
    def list_tags(
        self,
        limit: int = 100,
        params: Dict[str, Any] = {},
        paginate: bool = True
    ):
        '''
        >>> import os
        >>> client = PagerDutyTagsClient(auth_token=os.environ.get('AUTH_TOKEN'))
        >>> tags = client.list_tags()
        Executing HTTP get on https://api.pagerduty.com/tags
        >>> len(tags) > 0
        True
        '''
        if not params:
            params = {
                'query': '',
                'sort_by': 'name',
                'limit': limit,
            }
        params['limit'] = params.get('limit', limit)
        return self.do_request(
            url=self._default_url,
            entity_name=self._default_entity_name,
            params=params,
            paginate=paginate
        )

    @log_it
    def get_tag(
        self,
        tag_id: str,
        params: Dict[str, Any] = {}
    ):
        '''
        >>> import os
        >>> client = PagerDutyTagsClient(auth_token=os.environ.get('AUTH_TOKEN'))
        >>> tags = client.get_tag('PKYLUO6')
        Executing HTTP get on https://api.pagerduty.com/tags/PKYLUO6
        >>> len(tags) > 0
        True
        '''
        assert tag_id, f'Cannot get tag with tag id: {tag_id}'
        resp = self.do_request(
            url=f'{self._default_url}/{tag_id}',
            entity_name='tag',
            params=params
        )
        tag = None
        if len(resp) == 1:
            tag = resp[0]
        return tag

    @log_it
    def create_tag(self, label: str = '', summary: str = ''):
        '''No doctest so we don't affect state in production PagerDuty'''
        url = f'{self._endpoint}/tags'
        data = {
            'tag': {
                'type': 'tag',
                'label': str(label),
                'summary': str(summary)
            }
        }
        resp = self.do_request(
            url=self._default_url,
            entity_name='tag',
            method='post',
            data=json.dumps(data)
        )
        if len(resp) == 0:
            raise Exception('Failed to create tag')
        return resp[0]

    @log_it
    def delete_tag(self, tag_id: str = ''):
        '''No doctest so we don't affect state in production PagerDuty'''
        return self.do_request(
            url=f'{self._default_url}/{tag_id}',
            entity_name='tag',
            method='delete'
        )
