from django.contrib.gis.db import models

from tagulous.models import SingleTagField, TagField, TagTreeModel

from companies.models import Company

# Create your models here.

def categoryimage_path(instance, filename):
    """Add the instance's id to the path
    """
    return f"category/{instance.id}/{filename}"

class TreeTag(TagTreeModel):
    class TagMeta:
        initial = ""
        force_lowercase = False
        max_count=20
        protect_all = True
        # autocomplete_view = 'myapp.views.hobbies_autocomplete'


class CategoryTag(TagTreeModel):
    official = models.BooleanField('Oficial', default=False)
    image = models.ImageField('Imagen de la categoría', upload_to='categories/', null=True, blank=True)
    class TagMeta:
        initial = ""
        force_lowercase = False
        protect_all = True
        # autocomplete_view = 'myapp.views.hobbies_autocomplete'


class AttributeTag(TagTreeModel):

    class TagMeta:
        initial = ""
        force_lowercase = False
        max_count=20
        protect_all = True
        # autocomplete_view = 'myapp.views.hobbies_autocomplete'


def product_image_path(instance, filename):
    """Add the instance's id to the path
    """
    return f"products/{instance.id}/{filename}"


class Product(models.Model):

    SYNCHRONIZED = 'SYNCHRONIZED'
    IMPORTED = 'IMPORTED'
    MANUAL = 'MANUAL'

    SOURCES = (
        (SYNCHRONIZED, 'Sincronizado'),
        (IMPORTED, 'Importado'),
        (MANUAL, 'Manual'),
    )

    company = models.ForeignKey(Company, on_delete=models.DO_NOTHING, null=True, blank=True)
    sku = models.CharField('Referencia de producto', max_length=255, null=True, blank=True )
    name = models.CharField('Nombre del producto', max_length=500, null=True, blank=True)
    description = models.TextField('Descripción', null=True, blank=True)
    image = models.ImageField('Imagen del producto', upload_to=product_image_path, null=True, blank=True)
    url = models.URLField('URL del producto', null=True, blank=True, max_length=1000)
    price = models.DecimalField('Precio', max_digits=10, decimal_places=2, null=True, blank=True)
    shipping_cost = models.DecimalField('Gastos de envío', max_digits=10, decimal_places=2, null=True, blank=True)
    shipping_terms = models.TextField('Condiciones de envío', null=True, blank=True)
    source = models.CharField('Fuente', choices=SOURCES, max_length=25, null=True, blank=True)
    sourcing_date = models.DateTimeField('Fecha de importación original de producto', null=True, blank=True)
    update_date = models.DateTimeField('Fecha de actualización de producto', null=True, blank=True)
    discount = models.DecimalField('Descuento', max_digits=5, decimal_places=2, null=True, blank=True)
    stock = models.PositiveIntegerField('Stock', null=True, blank=True)
    tags = TagField(to=TreeTag, blank=True)
    category = SingleTagField(to=CategoryTag, null=True, blank=True, on_delete=models.SET_NULL) # main tag category
    attributes = TagField(to=AttributeTag, blank=True, related_name='product_attributes')
    identifiers = models.TextField('Identificador único de producto', null=True, blank=True)
    active = models.BooleanField('Activo', default=False)

    # internal
    created = models.DateTimeField('date of creation', auto_now_add=True)
    updated = models.DateTimeField('date last update', auto_now=True)
    creator = models.ForeignKey('core.CustomUser', on_delete=models.SET_NULL, null=True, blank=True, related_name='product')
    history = models.ForeignKey('history.HistorySync', on_delete=models.SET_NULL, null=True, blank=True, related_name='product')

    def __str__(self):
        return f"{self.name} / {self.sku}"

    class Meta:
        verbose_name = "Producto"
        verbose_name_plural = "Productos"
