# -*- coding: utf-8 -*-
from django.db import models
from django.contrib.auth.models import User, Permission
from django.db.models.signals import post_save, pre_delete, post_delete

import os
import settings

## ProductCategory Class
# 
class ProductCategory(models.Model):
	parent = models.ForeignKey('self', null=True) #Parent ID. If productCategory is NULL, this means the top level.	
	name = models.CharField(max_length=128)
	valid = models.BooleanField(default=True) #visible
	orderValue = models.IntegerField() #sort order
	
	def __unicode__(self):
		return self.name
	
	def get_level(self):
		category = self
		depth = 1
		while category.parent != None:
			depth += 1
			category = category.parent
		return depth
	
	class Meta:
		get_latest_by = 'orderValue'
		ordering = ['orderValue']

def rearrangeProductCategory(sender, instance, using, **kwargs):
	parentCategory = instance.parent
	siblings = sender.objects.filter(parent = parentCategory, valid = True).exclude(id = instance.id)
	for index, category in enumerate(siblings):
		category.orderValue = index
		category.save()

pre_delete.connect(rearrangeProductCategory, sender=ProductCategory)

def UploadProductFile(instance, filename):
	return filename
	
## Product Class
#
class Product(models.Model):
	category = models.ForeignKey('ProductCategory')
	type = models.IntegerField(default=1) #1: photo, 2: image
	code = models.CharField(max_length=20)
	name = models.CharField(max_length=128)
	layerCount = models.IntegerField() #layer count
	url = models.URLField(max_length=200) #real product url address for sale
	valid = models.BooleanField(default=False) #visible
	orderValue = models.IntegerField() #sort order
	
	image = models.ImageField(upload_to = UploadProductFile)
	thumb = models.ImageField(upload_to = UploadProductFile)
	txd = models.FileField(upload_to = UploadProductFile)
	xml = models.FileField(upload_to = UploadProductFile)
	
	def __unicode__(self):
		return self.name
	
	def str_allowed_group_ids(self):
		return '-'.join([str(clientGroup.id) for clientGroup in self.allowed_groups.all()])
	
	class Meta:
		get_latest_by = 'orderValue'
		ordering = ['orderValue']

def rearrangeProduct(sender, instance, using, **kwargs):
	category = instance.category
	siblings = sender.objects.filter(category = category, valid = True).exclude(id = instance.id)
	for index, product in enumerate(siblings):
		product.orderValue = index
		product.save()

pre_delete.connect(rearrangeProduct, sender=Product)

## DeleteProductData(Image, XML, TXD files)
# When you delete Product, automatically post delete ProductData
def delete_product_data(sender, instance, **kwargs):
	try:
		instance.image.delete(save=False)
		instance.thumb.delete(save=False)
		instance.txd.delete(save=False)
		instance.xml.delete(save=False)
	except:
		pass

post_delete.connect(delete_product_data, sender=Product)
