# -*- coding: utf-8 -*-
import json

from django.db import models

from events.geobase_contrib.managers import RegionManager
from events.common_app.models import Md5sumMixin
from events.translation.models import TranslationModel


class RegionBase(Md5sumMixin, TranslationModel):
    FIELDS_FOR_TRANSLATION = ('name', 'full_name')

    name = models.TextField('название')  # Москва
    full_name = models.TextField('полное название')  # Серпухов, Серпуховский район, Москва и Московская область, Россия

    objects = RegionManager()

    class Meta:
        ordering = ['name']
        abstract = True

    def __str__(self):
        # todo: test me
        return self.full_name or self.name

    @classmethod
    def calc_md5sum(cls, name, full_name, translations):
        return cls._calc_md5sum(
            name,
            full_name,
            json.dumps(translations, sort_keys=True, ensure_ascii=False),
        )

    def md5(self):
        return self.calc_md5sum(
            self.name,
            self.full_name,
            self.translations,
        )

    def get_name(self):
        return self.get_translated_field('name')

    def get_full_name(self):
        return self.get_translated_field('full_name')


class City(RegionBase):
    """Модель города

    @param geobase_id: разрешен null, чтобы иметь возможность в админке добавлять свои города без привязки к геобазе

    """
    geobase_id = models.PositiveIntegerField('ID в геобазе', blank=True, null=True, unique=True)
    country = models.ForeignKey('Country', verbose_name='страна', on_delete=models.DO_NOTHING)
    profiles_count = models.PositiveIntegerField('пользователей', default=0, db_index=True)

    class Meta:
        ordering = ['name']
        verbose_name = 'город'
        verbose_name_plural = 'города'

    @classmethod
    def calc_md5sum(cls, name, full_name, population, translations):
        return cls._calc_md5sum(
            name,
            full_name,
            str(population),
            json.dumps(translations, sort_keys=True, ensure_ascii=False),
        )

    def md5(self):
        return self.calc_md5sum(
            self.name,
            self.full_name,
            self.profiles_count,
            self.translations,
        )


class Country(RegionBase):
    """Модель страны"""
    geobase_id = models.PositiveIntegerField('ID в геобазе', unique=True)

    class Meta:
        ordering = ['name']
        verbose_name = 'страна'
        verbose_name_plural = 'страны'
