from collections import defaultdict

from django.contrib.auth import get_user_model
from django.db import transaction

from intranet.search.core.management.commands.yql_base import Command as BaseCommand


User = get_user_model()


class Command(BaseCommand):

    help = 'Collect data about most frequently searched people per user'
    default_period = 30
    job_name = 'calc_people_search_frequency'
    yql_script_name = 'get_people_search_frequency.yql'
    yql_attachments_files = BaseCommand.yql_attachments_files + ['libra_parse_clicks.py']

    def save_data(self, data):
        data = self._transform_data(data)
        self._update_users(data)

    def _transform_data(self, data):
        result = defaultdict(dict)
        for item in data:
            login = item['login']
            target_id = item['target_id']
            result[login][target_id] = item['clicks_count']
        return result

    @transaction.atomic
    def _update_users(self, data):
        users = User.objects.filter(username__in=data)
        for user in users:
            user.frequently_searched_people = data[user.username]
            user.save(update_fields=['frequently_searched_people'])
