import requests
import logging

from saas.library.python.token_store import PersistentTokenStore
from saas.library.python.token_store.errors import TokenGetFail


class Infra(object):
    def __init__(self, token=None):

        self.infra_token = token
        if not self.infra_token:
            try:
                self.infra_token = PersistentTokenStore.get_token_from_store_env_or_file('infra')
            except TokenGetFail:
                logging.warn("Can't obtain infra token. Readonly methods will be unauthorized")

        self.api_url = 'https://infra-api.yandex-team.ru/v1'
        self._session = requests.Session()
        headers = {'Content-Type': 'application/json'}
        if self.infra_token:
            headers.update({'Authorization': 'OAuth {}'.format(self.infra_token)})
        self._session.headers.update(headers)

    def list_environments(self, service):
        r = self._session.get(
            '{}/environments?serviceId={}'.format(self.api_url, service),
        )
        return r.json()

    def list_services(self):
        r = self._session.get(
            '{}/services'.format(self.api_url),
        )
        return r.json()

    def create_environment(self, service, environment):
        r = self._session.post(
            '{}/environments/'.format(self.api_url),
            json={
                "name": environment,
                "serviceId": service,
                "createCalendar": False
                }
        )
        r.raise_for_status()

    def environments_by_name(self, service=503):
        return {a['name']: a['id'] for a in self.list_environments(service)}

    def environments_by_id(self, service=503):
        return {a['id']: a['name'] for a in self.list_environments(service)}

    @property
    def services_by_name(self):
        return {a['service_name']: a['id'] for a in self.list_services()}

    @property
    def services_by_id(self):
        return {a['id']: a['service_name'] for a in self.list_services()}
