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

from django.db import models
from events.common_app.jsonfield.fields import JSONField as JSONFieldWithFallback
from events.common_app.utils import get_lang_with_fallback


class TranslationModel(models.Model):
    FIELDS_FOR_TRANSLATION = tuple()

    translations = JSONFieldWithFallback(null=True, blank=True)

    class Meta:
        abstract = True

    def get_translated_field(self, field_name):
        lang, fallback_lang = get_lang_with_fallback()

        translations = self.translations or {}
        trans_value = translations.get(field_name, {})
        if lang in trans_value:
            return trans_value.get(lang)
        if fallback_lang in trans_value:
            return trans_value.get(fallback_lang)

        return getattr(self, field_name)

    def set_translated_field(self, field_name, field_value):
        lang, _ = get_lang_with_fallback()

        translations = self.translations or {}
        trans_value = translations.get(field_name, {})
        trans_value[lang] = field_value
        translations[field_name] = trans_value

        self.translations = translations

    def get_default_language(self):
        raise NotImplementedError
