# -*- coding: utf-8 -*-

from django.db.models import Manager, When, Case, F, CharField, Value as V
from django.db.models.functions import Concat
from django.db.models.query import QuerySet
from events.data_sources.conditions import UniversityConditions


class DataSourceItemManager(Manager):
    def get_and_update(self, data_source, identity, **kwargs):
        obj, _ = self.get_or_create(data_source=data_source, identity=identity)
        if 'text' in kwargs:
            obj = self._update_translation(obj, kwargs['text'])
        return obj

    def get_and_update_bulk(self, data_source, items):
        response = [
            self._update_translation(dsi, items.get(dsi.identity))
            for dsi in self.filter(data_source=data_source, identity__in=items.keys())
        ]
        new_identities = set(items.keys()).difference(obj.identity for obj in response)
        if new_identities:
            objs = []
            for identity in new_identities:
                text = items[identity]
                dsi = self.model(
                    data_source=data_source,
                    identity=identity,
                    text=text,
                )
                dsi.set_translated_field('text', text)
                objs.append(dsi)
            self.model.objects.bulk_create(objs)
            response = self.filter(data_source=data_source, identity__in=items.keys())
        return response

    def _update_translation(self, dsi, text):
        translated_text = dsi.get_translated_field('text')
        if not translated_text:
            dsi.text = text
        if translated_text != text:
            dsi.set_translated_field('text', text)
            dsi.save(update_fields=['text', 'translations'])
        return dsi


class UniversityQuerySet(QuerySet):
    def filter_by_fit_for_search_text(self, search_text):
        return self.filter(UniversityConditions.is_fit_for_search_text(search_text=search_text))

    def annotate_full_name(self):
        return self.annotate(
            full_region=Case(
                When(city=F('region'), then=F('city')),
                default=Concat('city', V(', '), 'region'),
                output_field=CharField()
            ),
        ).annotate(full_name=Concat('name', V(', '), 'full_region'))


class UniversityManager(Manager):
    def get_queryset(self):
        return UniversityQuerySet(self.model, using=self._db)
