import logging
import requests

from pagerduty_api import log_it
from pagerduty_api.abstract_client import AbstractClient
from typing import List


class PagerDutyUsersClient(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}/users'
        self._default_entity_name = 'users'

    @log_it
    def list_users(
        self,
        team_ids: List[str] = [],
        limit: int = 100,
        paginate: bool = True
    ):
        '''
        >>> import os
        >>> client = PagerDutyUsersClient(auth_token=os.environ.get('AUTH_TOKEN'))
        >>> users = client.list_users(paginate=False)
        Executing HTTP get on https://api.pagerduty.com/users
        >>> len(users) > 0
        True
        '''
        return self.do_request(
            url=self._default_url,
            entity_name=self._default_entity_name,
            params={
                'team_ids[]': team_ids,
                'time_zone': 'UTC',
                'sort_by': 'name',
                'query': '',
                'limit': limit,
                'include[]': []
            },
            paginate=paginate
        )

    @log_it
    def list_users_by_team(
        self,
        team_ids: List[str] = [],
        limit: int = 100,
        paginate: bool = True
    ):
        '''
        >>> import os
        >>> client = PagerDutyUsersClient(auth_token=os.environ.get('AUTH_TOKEN'))
        >>> users_by_team = client.list_users_by_team(team_ids=['PUE38G0'])
        Executing HTTP get on https://api.pagerduty.com/users
        >>> len(users_by_team) == 1
        True
        '''
        users_dict = {} # team ID -> list of users
        for user in self.list_users(team_ids, limit, paginate):
            for team in user['teams']:
                if team['id'] not in team_ids:
                    continue
                if team['id'] not in users_dict:
                    users_dict[team['id']] = []
                users_dict[team['id']].append(user)
        return users_dict

    @log_it
    def get_user_by_id(self, user_id: str):
        '''
        >>> import os
        >>> client = PagerDutyUsersClient(auth_token=os.environ.get('AUTH_TOKEN'))
        >>> users = client.get_user_by_id('PN5ECJH')
        Executing HTTP get on https://api.pagerduty.com/users/PN5ECJH
        >>> len(users) > 0
        True
        '''
        return self.do_request(
            url=f'{self._default_url}/{user_id}',
            entity_name='user'
        )

    @log_it
    def get_user_by_email(self, email: str):
        '''
        >>> import os
        >>> client = PagerDutyUsersClient(auth_token=os.environ.get('AUTH_TOKEN'))
        >>> users = client.get_user_by_email('john.torres@pearson.com')
        Executing HTTP get on https://api.pagerduty.com/users
        >>> len(users) > 0
        True
        '''
        return self.do_request(
            url=self._default_url,
            entity_name=self._default_entity_name,
            params={
                'user_ids[]': [],
                'time_zone': 'UTC',
                'sort_by': 'name',
                'query': str(email),
                'include[]': []
            }
        )

    @log_it
    def is_valid_user(self, email: str):
        '''
        >>> import os
        >>> client = PagerDutyUsersClient(auth_token=os.environ.get('AUTH_TOKEN'))
        >>> b = client.is_valid_user('john.torres@pearson.com')
        Executing HTTP get on https://api.pagerduty.com/users
        >>> b
        True
        '''
        users = self.get_user_by_email(email)
        return len(users) > 0
