# -*- coding: utf-8 -*-
from django.db import models
from django.db.models.query import QuerySet

from events.music.client import MusicGenreClient
from events.common_app.managers import ProxyToQuerySetMixin
from events.translation.managers import TranslationQuerySetMixin


class MusicGenreQuerySet(TranslationQuerySetMixin, QuerySet):
    def filter_by_fit_for_search_text(self, search_text):
        return self.filter_translated_fields(search_text, 'title')


class MusicGenreManager(ProxyToQuerySetMixin, models.Manager):
    def get_queryset(self):
        return MusicGenreQuerySet(self.model, using=self._db)

    def sync_one_item(self, data, key_to_md5sum):
        music_id = data['music_id']
        title = data['title']
        translations = data['translations']
        md5sum = self.model.calc_md5sum(title, translations)

        if music_id not in key_to_md5sum:
            self.model.objects.create(
                music_id=music_id,
                title=title,
                translations=translations,
                md5sum=md5sum,
            )
        elif key_to_md5sum[music_id] != md5sum:
            self.model.objects.filter(music_id=music_id).update(
                title=title,
                translations=translations,
                md5sum=md5sum,
            )

    def sync_with_source(self):
        key_to_md5sum = dict(
            pair
            for pair in self.model.objects.values_list('music_id', 'md5sum')
        )
        sync_client = MusicGenreClient()
        for data in sync_client.make_request():
            self.sync_one_item(data, key_to_md5sum)
