# -*- 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
from product.models import Product
from PIL import Image

import os
import settings
import shutil

## FabricCategory Class
class FabricCategory(models.Model):
	name = models.CharField(max_length=128)
	valid = models.BooleanField(default=True) #visible
	orderValue = models.IntegerField() #sort order
	level = models.IntegerField(null = True, default = None)
	supercategory = models.ForeignKey('self', null=True, on_delete=models.CASCADE)
	
	def __unicode__(self):
		return self.name
	
	class Meta:
		get_latest_by = 'orderValue'
		ordering = ['orderValue']
		
def rearrangeFabricCategory(sender, instance, using, **kwargs):
	siblings = sender.objects.filter(valid = True).exclude(id = instance.id)
	for index, category in enumerate(siblings):
		category.orderValue = index
		category.save()

pre_delete.connect(rearrangeFabricCategory, sender=FabricCategory)

def UploadFabricImage(instance, filename):
	return filename
	
## Fabric Class
# thubmnail path: some directory/id.jpg
# real size image path: some directory/id.jpg
class Fabric(models.Model):
	name = models.CharField(max_length=128)
	valid = models.BooleanField(default=False) #Visible
	user = models.ForeignKey(User)
	
	category = models.ForeignKey('FabricCategory', null=True)
	orderValue = models.IntegerField()

	image = models.ImageField(upload_to = UploadFabricImage)
	thumb = models.ImageField(upload_to = UploadFabricImage)
	dpi = models.IntegerField(null = True, default = None)
	width = models.IntegerField(null = True, default = None)
	height = models.IntegerField(null = True, default = None)
	
	belonging = models.OneToOneField('BelongingToProduct', null=True, default=None)
	
	def __unicode__(self):
		return self.name
		
	class Meta:
		get_latest_by = 'orderValue'
		ordering = ['orderValue']

def rearrangeFabric(sender, instance, using, **kwargs):
	category = instance.category
	info_isnull = not hasattr(instance, 'fabricinformation')
	siblings = sender.objects.filter(category = category, fabricinformation__isnull = info_isnull, valid = True).exclude(id = instance.id)
	for index, fabric in enumerate(siblings):
		fabric.orderValue = index
		fabric.save()

pre_delete.connect(rearrangeFabric, sender=Fabric)

## Delete Fabric Data(Image files)
# When you delete Fabric, automatically post delete FabricData
def delete_fabric_data(sender, instance, **kwargs):
	try:
		instance.image.delete(save=False)
		instance.thumb.delete(save=False)
	except:
		pass
		
	detailImagesDir = '%sdata/fabric_details/%s/%s' % (settings.MEDIA_ROOT, str(instance.id/10000), str(instance.id))
	if os.path.exists(detailImagesDir):
		shutil.rmtree(detailImagesDir)

post_delete.connect(delete_fabric_data, sender=Fabric)		
	
## FabricInformation Class
# detail fabric information ( exists when a fabric has been uploaded by manager )
class FabricInformation(models.Model):
	fabric = models.OneToOneField('Fabric')
	
	code = models.CharField(max_length=20)
	weight = models.CharField(max_length=20)
	width = models.CharField(max_length=20)
	composition = models.CharField(max_length=20)
	price = models.CharField(max_length=20)
	oneRepeatSize = models.CharField(max_length=20)
	'''
	weightUnit = models.CharField(max_length=10) #g, kg, lb, oz, kun(korean), ...
	sizeUnit = models.CharField(max_length=10) #inch, cm, ft, yd, ...
	priceUnit = models.CharField(max_length=10) #KRW, USD, EUR, JPY, CNY,...
	
	oneRepeatWidth = models.IntegerField()
	oneRepeatHeight = models.IntegerField()
	oneRepeatSizeUnit = models.CharField(max_length=10) #inch, cm, ft, yd, ...
	'''
	text = models.CharField(max_length=400) # explanation
	
## BelongingToProduct Class
# fabric-product information ( exists when a fabric belongs to a product )
class BelongingToProduct(models.Model):
	product = models.ForeignKey(Product)
	
	layerName = models.CharField(max_length=128)
	layerIndex = models.IntegerField()
	groupIndex = models.IntegerField()
	grids = models.CharField(max_length=100)
	mask = models.ImageField(upload_to = UploadFabricImage)

## Delete BelongingToProduct Data(Mask files)
# When you delete Fabric, automatically post delete BelongingToProduct Data
def delete_belonging_data(sender, instance, **kwargs):
	try:
		instance.mask.delete(save=False)
	except:
		pass
	
post_delete.connect(delete_belonging_data, sender=BelongingToProduct)

## LaundryTags Class
# 
class LaundryTags(models.Model):
	fabricInfo = models.OneToOneField('FabricInformation')

	tag1 = models.BooleanField(default=False)
	tag2 = models.BooleanField(default=False)
	tag3 = models.BooleanField(default=False)
	tag4 = models.BooleanField(default=False)
	tag5 = models.BooleanField(default=False)
	tag6 = models.BooleanField(default=False)
	tag7 = models.BooleanField(default=False)

def create_laundrytags(sender, instance, created, **kwargs):
	if created:
		LaundryTags.objects.create(fabricInfo=instance)

post_save.connect(create_laundrytags, sender=FabricInformation)

# Clothes Image
class DetailImage(models.Model):
	fabric = models.ForeignKey(Fabric)
	image = models.ImageField(upload_to = UploadFabricImage)
	thumb = models.ImageField(upload_to = UploadFabricImage)
    
    

## SearchColor Class
# 
class SearchColor(models.Model):
	fabricInfo = models.OneToOneField('FabricInformation')

	option0 = models.BooleanField(default=False)
	option1 = models.BooleanField(default=False)
	option2 = models.BooleanField(default=False)
	option3 = models.BooleanField(default=False)
	option4 = models.BooleanField(default=False)
	option5 = models.BooleanField(default=False)
	option6 = models.BooleanField(default=False)
	option7 = models.BooleanField(default=False)
	option8 = models.BooleanField(default=False)

def create_searchcolor(sender, instance, created, **kwargs):
	if created:
		SearchColor.objects.create(fabricInfo=instance)

post_save.connect(create_searchcolor, sender=FabricInformation)


## SearchImage Class
# 
class SearchImage(models.Model):
	fabricInfo = models.OneToOneField('FabricInformation')

	option0 = models.BooleanField(default=False)
	option1 = models.BooleanField(default=False)
	option2 = models.BooleanField(default=False)
	option3 = models.BooleanField(default=False)
	option4 = models.BooleanField(default=False)
	option5 = models.BooleanField(default=False)
	option6 = models.BooleanField(default=False)
	option7 = models.BooleanField(default=False)
	option8 = models.BooleanField(default=False)

def create_searchimage(sender, instance, created, **kwargs):
	if created:
		SearchImage.objects.create(fabricInfo=instance)

post_save.connect(create_searchimage, sender=FabricInformation)


## SearchFunction Class
# 
class SearchFunction(models.Model):
	fabricInfo = models.OneToOneField('FabricInformation')

	option0 = models.BooleanField(default=False)
	option1 = models.BooleanField(default=False)
	option2 = models.BooleanField(default=False)
	option3 = models.BooleanField(default=False)
	option4 = models.BooleanField(default=False)
	option5 = models.BooleanField(default=False)
	option6 = models.BooleanField(default=False)
	option7 = models.BooleanField(default=False)
	option8 = models.BooleanField(default=False)

def create_searchfunction(sender, instance, created, **kwargs):
	if created:
		SearchFunction.objects.create(fabricInfo=instance)

post_save.connect(create_searchfunction, sender=FabricInformation)