# -*- coding: utf-8 -*-
import logging

from django.conf import settings
from django.utils import timezone
from requests.exceptions import HTTPError

from events.common_app.utils import requests_session
from events.yauth_contrib.auth import OAuth

logger = logging.getLogger(__name__)


class TankerClient:
    def __init__(self, project):
        self.project = project
        self.auth = OAuth(settings.TANKER_TOKEN)

    def _make_request(self, method, path, **kwargs):
        url = f'{settings.TANKER_URL}{path}'
        response = requests_session.request(method, url, auth=self.auth, **kwargs)
        response.raise_for_status()
        if response.content:
            return response.json()

    def get_keyset(self, keyset):
        path = f'/project/{self.project}/keyset/{keyset}/'
        try:
            return self._make_request('get', path)
        except HTTPError as e:
            if e.response.status_code == 404:
                logger.warning('Keyset %s not found', keyset)
                return None
            raise

    def create_keyset(self, keyset, languages=None, original_language=None):
        original_language = original_language or 'ru'
        languages = set(languages or settings.TANKER_LANGUAGES)
        languages.add(original_language)
        path = f'/project/{self.project}/keyset/'
        data = {
            'code': keyset,
            'name': keyset,
            'meta': {
                'languages': list(languages),
                'original_language': original_language,
                'auto_approve_original': True,
                'auto_approve': False,
            },
        }
        return self._make_request('post', path, json=data)

    def change_keyset(self, keyset, languages=None, original_language=None):
        original_language = original_language or 'ru'
        languages = set(languages or settings.TANKER_LANGUAGES)
        languages.add(original_language)
        path = f'/project/{self.project}/keyset/{keyset}/'
        data = {
            'code': keyset,
            'name': keyset,
            'status': 'ACTIVE',
            'meta': {
                'languages': list(languages),
                'original_language': original_language,
                'auto_approve_original': True,
                'auto_approve': False,
            },
        }
        return self._make_request('patch', path, json=data)

    def get_keys(self, keyset):
        path = f'/project/{self.project}/keyset/{keyset}/key/'
        result = self._make_request('get', path)
        return result['items']

    def _key_data(self, key_name, key_value, action=None, original_language=None):
        original_language = original_language or 'ru'
        action = action or 'CREATE'
        return {
            'name': key_name,
            'action': action,
            'plural': False,
            'translations': {
                original_language: {
                    'status': 'APPROVED',
                    'payload': {
                        'singular_form': key_value,
                    },
                },
            },
        }

    def change_keys(self, keyset, create_keys=None, update_keys=None, delete_keys=None, original_language=None):
        original_language = original_language or 'ru'
        path = f'/project/{self.project}/keyset/{keyset}/batch/'
        data = {
            'commit_message': f'Update keys {timezone.now()}',
        }
        if create_keys or update_keys:
            data['update'] = {
                'action': 'CREATE',
                'keys': [
                    self._key_data(
                        key_name, key_value,
                        action='CREATE',
                        original_language=original_language,
                    )
                    for (key_name, key_value) in (create_keys or {}).items()
                ] + [
                    self._key_data(
                        key_name, key_value,
                        action='UPDATE',
                        original_language=original_language,
                    )
                    for (key_name, key_value) in (update_keys or {}).items()
                ],
            }
        if delete_keys:
            data['delete'] = {
                'keys': delete_keys,
            }
        return self._make_request('post', path, json=data)

    def get_keysets(self):
        path = f'/project/{self.project}/keyset/'
        result = self._make_request('get', path)
        return result['items']
