# -*- coding: UTF-8 -*-
import os
from django.db import models
from django.utils.timezone import now as timezone_now
from django.utils.translation import ugettext_lazy as _
from django.core.urlresolvers import reverse
from django.core.urlresolvers import NoReverseMatch

from utils.models import UrlMixin


def upload_to(instance, filename):
    now = timezone_now()
    filename_base, filename_ext = os.path.splitext(filename)
    return 'products/%s/%s%s' % (
        instance.product.slug,
        now.strftime("%Y%m%d%H%M%S"),
        filename_ext.lower(),
    )


class Product(UrlMixin):
    title = models.CharField(_(u"tytuł"), max_length=200)
    slug = models.SlugField(_(u"slug"), max_length=200)
    description = models.TextField(_("opis"), blank=True)
    price = models.DecimalField(_(u"cena (€)"), max_digits=8, decimal_places=2, blank=True, null=True)

    class Meta:
        verbose_name = _("Produkt")
        verbose_name_plural = _("Produkty")

    def __unicode__(self):
        return self.title

    def get_url_path(self):
        try:
            return reverse('product_detail', kwargs={'slug': self.slug})
        except NoReverseMatch:
            return ""


class ProductPhoto(models.Model):
    product = models.ForeignKey(Product)
    photo = models.ImageField(_("photo"), upload_to=upload_to)

    class Meta:
        verbose_name = _(u"Zdjęcie")
        verbose_name_plural = _(u"Zdjęcia")

    def __unicode__(self):
        return self.photo.name
