"""This module holds the models of the ``themes`` app."""

from django.conf import settings
from django.db import models
from django.utils.functional import cached_property
from django.utils.translation import ugettext_lazy as _

from mtp.apps.common.constants import RESOLUTIONS
from mtp.apps.common.utils import compute_file_field_hash
from mtp.apps.sync.models import Syncable
from mtp.apps.themes.managers import ThemeManager

from . import constants


class Theme(Syncable):
    """Django model representing a theme.

    A theme is composed by a set of colors and images, allowing the customization of the look
    of the front-end applications and the cms.

    """

    class Meta:
        ordering = ("-default", "name")

    name = models.CharField(max_length=200)
    default = models.BooleanField(default=False)

    # "Old" fields, to be deprecated.
    color_first = models.CharField(max_length=10, default=settings.THEME_COLOR_FIRST)
    color_second = models.CharField(max_length=10, default=settings.THEME_COLOR_SECOND)
    color_item = models.CharField(max_length=10, default=settings.THEME_COLOR_ITEM)
    color_selected_item = models.CharField(
        max_length=10,
        default=settings.THEME_COLOR_SELECTED_ITEM)
    color_text_item = models.CharField(max_length=10, default=settings.THEME_COLOR_TEXT_ITEM)
    color_text_selected_item = models.CharField(
        max_length=10,
        default=settings.THEME_COLOR_TEXT_SELECTED_ITEM)
    color_text_quizz = models.CharField(max_length=10, default=settings.THEME_COLOR_TEXT_QUIZZ)
    background_color = models.CharField(max_length=10, default=settings.THEME_BACKGROUND_COLOR)
    background_color_diffusion = models.CharField(
        max_length=10,
        default=settings.THEME_BACKGROUND_COLOR_DIFFUSION)

    background_image = models.ImageField(
        upload_to="training",
        blank=True,
        default=settings.THEME_BACKGROUND_IMAGE)
    background_image_hash = models.CharField(max_length=36, blank=True, null=True)
    background_image_diffusion = models.ImageField(
        upload_to="training",
        blank=True,
        default=settings.THEME_BACKGROUND_IMAGE_DIFFUSION)
    background_image_diffusion_hash = models.CharField(max_length=36, blank=True, null=True)

    # "New" fields.
    main = models.CharField(max_length=64, blank=True)
    main_lighter = models.CharField(max_length=64, blank=True)
    main_darker = models.CharField(max_length=64, blank=True)

    complementary = models.CharField(max_length=64, blank=True)

    clear = models.CharField(max_length=64, blank=True)

    background = models.CharField(max_length=64, blank=True)

    gray = models.CharField(max_length=64, blank=True)
    gray_lighter = models.CharField(max_length=64, blank=True)
    gray_darker = models.CharField(max_length=64, blank=True)

    text_on_main = models.CharField(max_length=64, blank=True)
    text_on_main_lighter = models.CharField(max_length=64, blank=True)
    text_on_main_darker = models.CharField(max_length=64, blank=True)
    text_on_complementary = models.CharField(max_length=64, blank=True)
    text_on_clear = models.CharField(max_length=64, blank=True)

    accent_blue = models.CharField(max_length=64, blank=True)
    accent_green = models.CharField(max_length=64, blank=True)
    accent_yellow = models.CharField(max_length=64, blank=True)
    accent_pink = models.CharField(max_length=64, blank=True)
    accent_red = models.CharField(max_length=64, blank=True)
    accent_white = models.CharField(max_length=64, blank=True)

    font_name = models.CharField(max_length=64, blank=True)
    font_bold_name = models.CharField(max_length=64, blank=True)
    font_thin_name = models.CharField(max_length=64, blank=True)

    brand_logo = models.ImageField(
        upload_to='theme',
        help_text=_('Choose a logo which represents your brand. '
                    'This logo is displayed in the top left corner in the cms'),
        verbose_name=_('brand logo'),
        blank=True,
        default=constants.DEFAULT_BRAND_LOGO_PATH
    )

    header_image = models.ImageField(
        upload_to="training",
        help_text=_('Preferred size: %(retina_width)dx%(retina_height)dpx (Retina) '
                    'or %(normal_width)dx%(normal_height)dpx (Normal)') % RESOLUTIONS,
        verbose_name=_('Header Image'),
        blank=True,
        default=settings.THEME_HEADER_IMAGE)
    header_image_hash = models.CharField(_('Header Image Hash'), max_length=64, blank=True)

    home_diffusion_image = models.ImageField(upload_to="training",
                                             verbose_name=_('Home Diffusion Image'),
                                             blank=True,
                                             default=settings.THEME_HOME_DIFFUSION_IMAGE)
    home_diffusion_image_hash = models.CharField(_('Home Diffusion Image Hash'),
                                                 max_length=64, blank=True)

    objects = ThemeManager()

    def get_sync_files(self):
        return [
            {
                "name": self.background_image.name,
                "hash": self.background_image_hash,
            },
            {
                "name": self.background_image_diffusion.name,
                "hash": self.background_image_diffusion_hash,
            },
            {
                "name": self.header_image.name,
                "hash": self.header_image_hash,
            },
            {
                "name": self.home_diffusion_image.name,
                "hash": self.home_diffusion_image_hash,
            },
        ]

    def __str__(self):
        return self.default and "%s (%s)" % (self.name, _("default")) or self.name

    def save(self, *args, **kwargs):
        if self.default:
            # We cannot use ``update`` because it does not call the ``save`` method and the
            # ``Syncable`` models need to call the ``save`` method for each update.
            for theme in Theme.objects.filter(default=True):
                if theme.pk == self.pk:
                    continue
                theme.default = False
                theme.save()

        # Create hash image
        self.background_image_hash = compute_file_field_hash(self.background_image)
        self.background_image_diffusion_hash = compute_file_field_hash(
            self.background_image_diffusion
        )
        self.header_image_hash = compute_file_field_hash(self.header_image)
        self.home_diffusion_image_hash = compute_file_field_hash(self.home_diffusion_image)

        # If no brand logo is defined (field is cleared by example), we use the default brand logo
        if not self.brand_logo:
            self.brand_logo = constants.DEFAULT_BRAND_LOGO_PATH

        super(Theme, self).save(*args, **kwargs)

    @cached_property
    def media_files(self):
        """Get the list of media file paths for this theme

        Returns
        -------
        list(str)
            A list of media relative paths for this theme

        """

        return [
            self.background_image.name,
            self.background_image_diffusion.name,
            self.header_image.name,
            self.home_diffusion_image.name
        ]
