import logging

from collections import defaultdict

from intranet.search.core.sources.utils import normalize, get_metrix_data

from intranet.search.core.utils.cache import CacheAdapter

log = logging.getLogger(__name__)

types = {
    'library': {
        'ru': 'Библиотека',
        'en': 'Library'
    },
    'block': {
        'ru': 'Блок',
        'en': 'Block'
    },
    'doc': {
        'ru': 'Статья',
        'en': 'Article'
    },
    '': {
        'ru': 'Неизвестно',
        'en': 'Unknown'
    },
    'technology': {
        'ru': 'Технология',
        'en': 'Technology'
    }
}


class Metrix(CacheAdapter):
    def __init__(self, cache, index):
        name = '%s_' % index
        self.index = index
        super().__init__(cache, name)

    def prepare_metrix(self, views_norm=100):
        try:
            data = get_metrix_data(self.index)
        except Exception as e:
            log.error(e)
            return

        libraries = defaultdict(int)

        for entry in data:
            try:
                self.set(entry['path'], normalize(entry['page_views'], views_norm))
            except Exception:
                log.warning('Error while setting views for %s' % entry['path'])
                continue

            parts = [p for p in entry['path'].split('/') if p]
            if len(parts) > 1 and parts[0] == 'libs':
                libraries[parts[1]] += entry['page_views']

        if libraries:
            norm = float(max(libraries.values()))
            for k, v in libraries.items():
                self.set(k, v/norm)
