import json
import logging
from typing import Any, Optional

import requests

from pagerduty_api import log_it
from pagerduty_api.abstract_client import AbstractClient


class PagerDutyTeamsClient(AbstractClient):

    def __init__(
        self,
        http_session: requests.Session = requests.Session(),
        endpoint: str = "https://api.pagerduty.com",
        auth_token: Optional[str] = None,
        logger: Optional[logging.Logger] = None,
    ):
        super().__init__(http_session, endpoint, auth_token, logger)
        self._default_url = f"{self._endpoint}/teams"
        self._default_entity_name = "teams"

    @log_it
    def list_teams(self, limit: int = 100, paginate: bool = True):
        """
        >>> import os
        >>> client = PagerDutyTeamsClient(auth_token=os.environ.get('AUTH_TOKEN'))
        >>> teams = client.list_teams()
        Executing HTTP get on https://api.pagerduty.com/teams
        >>> len(teams) > 0
        True
        """
        return self.do_request(
            url=self._default_url,
            entity_name=self._default_entity_name,
            params={"limit": limit},
            paginate=paginate,
        )

    @log_it
    def get_team(
        self, team_id: str, with_members: bool = False, params: Optional[dict[str, Any]] = None
    ):
        """
        >>> import os
        >>> client = PagerDutyTeamsClient(auth_token=os.environ.get('AUTH_TOKEN'))
        >>> teams = client.get_team('PUE38G0')
        Executing HTTP get on https://api.pagerduty.com/teams/PUE38G0
        >>> len(teams) > 0
        True
        >>> teams = client.get_team('PUE38G0', with_members=True)
        Executing HTTP get on https://api.pagerduty.com/teams/PUE38G0
        Executing HTTP get on https://api.pagerduty.com/teams/PUE38G0/members
        >>> len(teams['members']) > 0
        True
        """
        resp = self.do_request(
            url=f"{self._default_url}/{team_id}", entity_name="team", params=params
        )
        if len(resp) == 0:
            return None

        team = resp[0]
        if with_members:
            team["members"] = self.get_team_members(team_id)
        return team

    @log_it
    def get_team_members(self, team_id: str):
        """
        >>> import os
        >>> client = PagerDutyTeamsClient(auth_token=os.environ.get('AUTH_TOKEN'))
        >>> members = client.get_team_members('PUE38G0')
        Executing HTTP get on https://api.pagerduty.com/teams/PUE38G0/members
        >>> len(members) > 0
        True
        """
        return self.do_request(url=f"{self._default_url}/{team_id}/members", entity_name="members")

    @log_it
    def is_member_of_team(self, team_id: str = "", user_id: str = "") -> bool:
        """
        >>> import os
        >>> client = PagerDutyTeamsClient(auth_token=os.environ.get('AUTH_TOKEN'))
        >>> b = client.is_member_of_team('PUE38G0', 'PN5ECJH')
        Executing HTTP get on https://api.pagerduty.com/teams/PUE38G0/members
        >>> b
        True
        """
        for user in self.get_team_members(team_id):
            if user["user"]["id"] == user_id:
                return True
        return False

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

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