# -*- coding: utf-8 -*-
from typing import List

from urllib.parse import urljoin
from django.conf import settings

from events.common_app.clients import BaseClient
from events.common_app.utils import requests_session
from events.yauth_contrib.auth import TvmAuth


ROLE_TVM_MANAGER = 'tvm_manager'
ROLE_FORM_MANAGER = 'form_manager'


class AbcServiceClient(BaseClient):
    def get_params(self):
        return {
            'page_size': 250,
            'fields': 'id,slug,name,state',
        }

    def get_auth(self):
        return TvmAuth(settings.ABC_TVM2_CLIENT)

    def get_url(self):
        return urljoin(settings.ABC_API_URL, 'services/')

    def process_one_item(self, item):
        yield {
            'abc_id': item['id'],
            'slug': item['slug'],
            'is_deleted': item['state'] == 'deleted',
            'is_active': item['state'] == 'develop',
            'name': item['name'].get('ru'),
            'translations': {
                'name': item['name'],
            },
        }


class AbcClient:
    def __init__(self):
        self.auth = TvmAuth(settings.ABC_TVM2_CLIENT)

    def _make_request(self, path, params):
        url = f'{settings.ABC_API_URL}{path}'
        response = requests_session.get(url, params=params, auth=self.auth)
        if response.status_code == 200:
            return response.json()

    def get_services_by_tvm_client(self, tvm_client: str):
        path = 'resources/consumers/'
        params = {
            'supplier': 14,
            'resource__external_id': tvm_client,
            'fields': 'service.id',
        }
        data = self._make_request(path, params)
        if data:
            results = data.get('results') or []
            for item in results:
                yield item['service']['id']

    def has_roles_in_service(self, service_id: int, role_codes: List[str], login: str = None, uid: str = None):
        assert login or uid, 'You must assign user login or uid'
        path = 'services/members/'
        params = {
            'service': service_id,
            'role__code__in': ','.join(role_codes),
            'fields': 'id',
        }
        if uid:
            params['person__uid'] = uid
        elif login:
            params['person__login'] = login
        data = self._make_request(path, params)
        if data:
            return bool(data.get('results'))
        return False
