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

from django.conf import settings
from events.common_app.utils import requests_session

GEOBASE_URL = 'http://geobase.qloud.yandex.ru/v1'
logger = logging.getLogger(__name__)


class GeobaseClient:
    timeout = (1, 10)

    def _make_request(self, path, params):
        url = f'{GEOBASE_URL}{path}'
        response = requests_session.get(
            url,
            params=params,
            verify=settings.YANDEX_ROOT_CERTIFICATE,
            timeout=self.timeout,
        )
        response.raise_for_status()
        return response.json()

    def get_region_by_id(self, region_id):
        params = {
            'id': region_id,
        }
        return self._make_request('/region_by_id', params)

    def get_region_by_ip(self, ip_address):
        params = {
            'ip': ip_address,
        }
        return self._make_request('/region_by_ip', params)

    def get_regions_by_type(self, region_type):
        params = {
            'type': region_type,
        }
        return self._make_request('/regions_by_type', params)

    def _get_item(self, it):
        return {
            'id': str(it['id']),
            'type': it['type'],
            'parent_id': str(it['parent_id']),
            'name': it['name'],
            'en_name': it['en_name'],
            'population': it.get('population', 0),
        }

    def get_geobase_data(self):
        geobase = {}
        region_types = [2, 3, 4, 5, 6, 7, 8, 10, 12, 13, 15]
        for region_type in region_types:
            regions = self.get_regions_by_type(region_type)
            logger.info(f'Read {len(regions)} regions with type {region_type}')
            for it in regions:
                region_id = str(it['id'])
                geobase[region_id] = self._get_item(it)
        return geobase

    def write_geobase_data(self, file_name=None):
        file_name = file_name or 'geobase.json'
        with open(file_name, 'w') as f:
            json.dump(self.get_geobase_data(), f)

    def read_geobase_data(self, file_name=None):
        file_name = file_name or 'geobase.json'
        with open(file_name, 'r') as f:
            return json.load(f)

    def _get_regions(self, region, geobase, _stack=None):
        _stack = _stack or []
        _stack.append(region)
        parent_id = region['parent_id']
        if parent_id in geobase:
            parent_id = self._get_regions(geobase[parent_id], geobase, _stack)
        return _stack

    def _get_country(self, regions):
        for it in regions:
            if it['type'] == 3:
                return it
        return regions[-1]

    def _get_full_name(self, regions, attr_name):
        return ', '.join(
            it[attr_name]
            for it in regions
            if it['type'] in (3, 5, 6, 7)
        )

    def get_cities(self, geobase):
        for it in geobase.values():
            if it['type'] in (6, 7):
                regions = self._get_regions(it, geobase)
                country = self._get_country(regions)
                full_name = self._get_full_name(regions, 'name')
                en_full_name = self._get_full_name(regions, 'en_name')
                yield {
                    'id': it['id'],
                    'name': it['name'],
                    'full_name': full_name,
                    'translations': {
                        'name': {
                            'ru': it['name'],
                            'en': it['en_name'],
                        },
                        'full_name': {
                            'ru': full_name,
                            'en': en_full_name,
                        },
                    },
                    'country': country,
                    'population': it['population'],
                }

    def get_countries(self, cities):
        country_set = set()
        for it in cities:
            country = it['country']
            country_id = country['id']
            if country_id not in country_set:
                country_set.add(country_id)
                yield {
                    'id': country_id,
                    'name': country['name'],
                    'full_name': country['name'],
                    'translations': {
                        'name': {
                            'ru': country['name'],
                            'en': country['en_name'],
                        },
                        'full_name': {
                            'ru': country['name'],
                            'en': country['en_name'],
                        },
                    },
                }
