# -*- coding: utf-8 -*-
from cms.models.fields import PlaceholderField
import os
from django.contrib.auth.models import Group, User
from django.core.files.storage import default_storage
from django.conf import settings
from django.db import models
from django.core.urlresolvers import reverse_lazy
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
from image_cropping import ImageRatioField
from parler.models import TranslatableModel, TranslatedFields

#from portal.storage import PrivateS3MediaStorage
from project.utils import CroppableFilerImageField


class Profile(models.Model):
    user = models.OneToOneField(User, related_name='profile', on_delete=models.CASCADE)
    first_name = models.CharField(verbose_name=_('Vorname'), max_length=255)
    last_name = models.CharField(verbose_name=_('Nachname'), max_length=255)
    street = models.CharField(verbose_name=_('Strasse'), max_length=255, null=True, blank=True)
    zip = models.IntegerField(verbose_name=_('PLZ'), null=True, blank=True)
    place = models.CharField(verbose_name=_('Ort'), max_length=255, null=True, blank=True)
    email = models.EmailField(verbose_name=_('E-Mail'), null=True, blank=True)

    class Meta:
        verbose_name = 'User Profil'
        verbose_name_plural = 'User Profile'

    def __str__(self):
        return self.full_name

    @property
    def full_name(self):
        return '{} {}'.format(self.first_name, self.last_name)


class Information(TranslatableModel):
    groups = models.ManyToManyField(Group, verbose_name='Mitglieder Gruppe', related_name='tasks')
    image = CroppableFilerImageField(verbose_name='Bild', blank=True, null=True)
    cropping = ImageRatioField('image', '1200x800', free_crop=True)

    placeholder = PlaceholderField('content')

    published = models.BooleanField(verbose_name='Veröffentlicht', default=False)
    updated = models.DateTimeField(verbose_name='Aktualisiert', auto_now=True)
    informed_users = models.ManyToManyField(User, verbose_name='Als gelesen markiert von:', null=True, blank=True)

    translations = TranslatedFields(
        title=models.CharField(max_length=100, verbose_name='Title'),
    )

    class Meta:
        verbose_name = 'Information'
        verbose_name_plural = 'Informationen'
        ordering = ['-updated']

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse_lazy('portal:information', args=[self.pk])


class DownloadSection(TranslatableModel):
    translations = TranslatedFields(
        title=models.CharField(max_length=100, verbose_name='Title')
    )
    ordering = models.IntegerField(default=50, verbose_name='Sortierung')

    class Meta:
        verbose_name = 'Download Section'
        verbose_name_plural = 'Download Sections'
        ordering = ['ordering']

    def __str__(self):
        return self.title


class DownloadTag(TranslatableModel):
    translations = TranslatedFields(
        name=models.CharField(max_length=100, verbose_name='Name')
    )

    class Meta:
        verbose_name = 'Download Tag'
        verbose_name_plural = 'Download Tags'

    def __str__(self):
        return self.name


if getattr(settings, 'DEFAULT_STORAGE_DSN', None):
    # protected_file_storage = PrivateS3MediaStorage()
    protected_file_storage = default_storage
else:
    protected_file_storage = default_storage


class DownloadFile(TranslatableModel):
    section = models.ForeignKey(DownloadSection, verbose_name='Download Section', related_name='files')
    groups = models.ManyToManyField(Group, verbose_name='Mitgliedergruppen', related_name='files')
    tags = models.ManyToManyField(DownloadTag, verbose_name='Suchbegriffe', related_name='files',
                                  blank=True, null=True)

    translations = TranslatedFields(
        name=models.CharField(max_length=512, verbose_name='Name', blank=True, null=True),
        description=models.TextField(verbose_name='Beschreibung', blank=True, null=True),
        file=models.FileField(upload_to='protected_files', max_length=512, storage=protected_file_storage)
    )

    ordering = models.IntegerField(default=50, verbose_name='Sortierung')

    class Meta:
        verbose_name = 'Download File'
        verbose_name_plural = 'Download Files'
        ordering = ['ordering']

    def __str__(self):
        return self.label

    @property
    def url(self):
        return self.file.url

    @property
    def extension(self):
        return self.file.name.split('.')[-1]

    @property
    def label(self):
        if self.name:
            return self.name
        else:
            return os.path.basename(self.file.name)

    @property
    def tag_list(self):
        return ', '.join(list(self.tags.values_list('translations__name', flat=True)))
