import os

from requests import Session

from bitrise.services import Bitrise


class BitriseClient(object):
    def __init__(self, api_token=None):
        """Client handling communication with Bitrise services

        Args:
            bitrise_token (str): API Token generated by Bitrise in account settings. Can be passed
                                 in explicitly, or set as environment variable BITRISE_TOKEN
        """

        auth_token = api_token or os.environ['BITRISE_TOKEN']

        if not auth_token:
            raise ValueError(
                'Must provide a bitrise token - set BITRISE_TOKEN environment variable or pass a '
                'token into call to BitriseClient'
            )

        self.auth_token = auth_token
        self.session = Session()
        self._add_auth_header()

    @property
    def bitrise(self):
        return Bitrise()

    @property
    def apps(self):
        resp_json = self.bitrise.apps.get(session=self.session).json()
        return resp_json['data']

    def _add_auth_header(self):
        auth_header = {'Authorization': f'token {self.auth_token}'}
        self.session.headers.update(auth_header)
