# -*- coding: utf-8 -*-
from django.template import RequestContext
from django.shortcuts import render_to_response
from django.contrib.auth.models import User, Permission
from django.http import HttpResponseRedirect, HttpResponse, Http404
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth.decorators import login_required, user_passes_test
from django.core.exceptions import ObjectDoesNotExist
from cStringIO import StringIO
from django.core.files.base import ContentFile
from django.db.models import Q
from django.core.files import File
from users.models import *
from fabric.models import *
from product.models import *
from PIL import Image
from common.common import *
from common.image import handleUploadedImg
from common.exception import UploadedImgFileError
from users.user_check import admin_check

import json
import os
import math
import settings
import string
import random
import imghdr

## get FabricCategoty list
# Return: xml - FabricCategory list
def getFabricCategoryList(request):
	type = int(request.POST['Type']) if request.POST.has_key('Type') else 2
	valid = request.POST['Visible'].lower() == 'true' if request.POST.has_key('Visible') else True
	level = request.POST.get('level', 0)
	supercid = request.POST.get('supercid', '')
	supersupercid = request.POST.get('supersupercid', '')

	if level == '1':
		categoryList = FabricCategory.objects.filter(valid = valid, level = level)
	elif level == '2':
		supercategory = FabricCategory.objects.get(id = supercid)
		categoryList = FabricCategory.objects.filter(valid = valid, level = level, supercategory = supercategory)
	else:
		if supersupercid == '':
			supercategory = FabricCategory.objects.get(id = supercid)
			categoryList = FabricCategory.objects.filter(valid = valid, level = level, supercategory = supercategory)
		else:
			supersupercategory = FabricCategory.objects.get(id = supersupercid)
			supercategory_list = FabricCategory.objects.filter(supercategory = supersupercategory)
			categoryList = FabricCategory.objects.filter(valid = valid, level = level, supercategory__in = supercategory_list)
			
	variables = {'categoryList': categoryList, 'type': type, 'level': level}
	return render_to_response('xml/categorylist.xml', RequestContext(request, variables))

## create FabricCategory
# Return: json - {success: True/False, [id: <created_category_id>]}
def createFabricCategory(request):
	try:
		name = request.POST['name']
		level = request.POST['level']
		supercid = request.POST.get('supercid', '')
	except:
		raise Http404
	try:
		orderValue = FabricCategory.objects.filter(valid = True, level = level).latest().orderValue + 1
	except ObjectDoesNotExist:
		orderValue = 0
	
	# check duplicated name
	if supercid == '':
		category = FabricCategory(name = name, orderValue = orderValue, level = level)
	else:
		supercategory = FabricCategory.objects.get(id = supercid)
		if FabricCategory.objects.filter(name = name, level = level, supercategory = supercategory).exists():
			variables = {'success': False, 'reason': 'NameAlreadyExists'}
			return HttpResponse(json.dumps(variables), mimetype='application/json')
		category = FabricCategory(name = name, orderValue = orderValue, level = level, supercategory = supercategory)
	category.save()

	variables = {'success': True, 'id': category.id}
	return HttpResponse(json.dumps(variables), mimetype='application/json')

## modify FabricCategory name
# Return: json - {success: True/False}
def modifyFabricCategory(request):
	try:
		categoryId = int(request.POST['cid'])
		new_name = request.POST['name']
	except:
		raise Http404
	
	try:
		category = FabricCategory.objects.get(id = categoryId)
	except ObjectDoesNotExist:
		variables = {'success': False, 'reason': 'DoesNotExist'}
		return HttpResponse(json.dumps(variables), mimetype='application/json')
	
	# check duplicated name
	
	if category.level > 1:
		supercategory = category.supercategory
		if FabricCategory.objects.filter(valid = True, name = new_name, supercategory=supercategory).exists():
			variables = {'success': False, 'reason': 'NameAlreadyExists'}
			return HttpResponse(json.dumps(variables), mimetype='application/json')
	else:
		if FabricCategory.objects.filter(valid = True, name = new_name).exists():
			variables = {'success': False, 'reason': 'NameAlreadyExists'}
			return HttpResponse(json.dumps(variables), mimetype='application/json')
	category.name = new_name
	category.save()
	
	variables = {'success': True}
	return HttpResponse(json.dumps(variables), mimetype='application/json')

## delete FabricCategory
# Return: json - {success: True/False}
def deleteFabricCategory(request):
	try:
		categoryId = int(request.POST['cid'])
	except:
		raise Http404
	
	try:
		category = FabricCategory.objects.get(id = categoryId)
	except ObjectDoesNotExist:
		variables = {'success': False, 'reason': 'DoesNotExist'}
		return HttpResponse(json.dumps(variables), mimetype='application/json')
	
	category.delete()
	
	variables = {'success': True}
	return HttpResponse(json.dumps(variables), mimetype='application/json')

## switch two FabricCategory orderValue
# Return: json - {success: True/False}
def switchFabricCategoryOrder(request):
	try:
		srcCategoryId = int(request.POST['scid'])
		dstCategoryId = int(request.POST['dcid'])
	except:
		raise Http404
	
	try:
		srcCategory = FabricCategory.objects.get(id = srcCategoryId)
		dstCategory = FabricCategory.objects.get(id = dstCategoryId)
	except ObjectDoesNotExist:
		raise Http404
	
	if abs(srcCategory.orderValue - dstCategory.orderValue) != 1:
		raise Http404
	
	(srcCategory.orderValue, dstCategory.orderValue) = (dstCategory.orderValue, srcCategory.orderValue)
	srcCategory.save()
	dstCategory.save()
	
	variables = {'success': True}
	return HttpResponse(json.dumps(variables), mimetype='application/json')

@csrf_exempt
def getBelongs(request):
	try:
		layerName = request.POST['layerName']
		pid = request.POST['pid']
		type = request.POST['type']
	except:
		raise Http404	
	belongList = BelongingToProduct.objects.filter(product__id=pid, layerName=layerName).order_by('id')
	if type == 'json':
		idList = []
		for belong in belongList:
			idList.append(belong.fabric.id)
		variables = {'idList': idList}	
		return HttpResponse(json.dumps(variables), mimetype='application/json')
	elif type == 'xml':
		variables = {'belongList': belongList}
		return render_to_response('xml/belongs.xml', RequestContext(request, variables))
	else:
		raise Http404

def getTargets(request):
	id = request.POST['fid']
	fabric = Fabric.objects.get(id = id)
	if fabric.image:
		image_url = fabric.image.url
	else:
		image_url = null
	if fabric.thumb:
		thum_url = fabric.thumb.url
	else:
		thum_url = null
	if fabric.belonging:
		mask = fabric.belonging.mask.url
	else: 
		mask = 0
	variables = {'name':fabric.name, 'id':fabric.id, 'width':fabric.width, 'height':fabric.height, 'path':image_url, 'thum_url':thum_url, 'mask':mask}
	return HttpResponse(json.dumps(variables), mimetype='application/json')
'''	
	newList = []
	try:
		idList = request.POST['idList']
	except:
		raise Http404
	idList = str(idList)
	idList = idList.split(';')
	for id in idList:
		newList.append(int(id))
	print newList
	fabricList = Fabric.objects.filter(id__in = newList)
	print fabricList
	variables = {'fabricList': fabricList}
	return render_to_response('xml/fabriclist.xml', RequestContext(request, variables))
'''	

def getFabricList(request):
	user = request.user
	categoryId = request.POST['cid']
	valid = request.POST['Visible'].lower() == 'true' if request.POST.has_key('Visible') else True
	level = request.POST['level']
	uppercategory = request.POST.get('uppercategory', '')
	'''
	if level == '1':
		supersupercategory = FabricCategory.objects.get(id = uppercategory)
		supercategory_list = FabricCategory.objects.filter(supercategory = supersupercategory)
		categoryList = FabricCategory.objects.filter(supercategory__in = supercategory_list)
		fabricList = Fabric.objects.filter(fabricinformation__isnull = False, category__in = categoryList)
	elif level == '2':
		supercategory = FabricCategory.objects.get(id = uppercategory)
		categoryList = FabricCategory.objects.filter(supercategory = supercategory)
		fabricList = Fabric.objects.filter(fabricinformation__isnull = False, category__in = categoryList)
	else:
		category = FabricCategory.objects.get(id = categoryId)
		fabricList = Fabric.objects.filter(fabricinformation__isnull = False, category = category)
		print fabricList
	'''
	if user.is_authenticated():
	
		if level == '1':
			supersupercategory = FabricCategory.objects.get(id = uppercategory)
			supercategory_list = FabricCategory.objects.filter(supercategory = supersupercategory)
			categoryList = FabricCategory.objects.filter(supercategory__in = supercategory_list)
			fabricList = Fabric.objects.filter(fabricinformation__isnull = False, category__in = categoryList)
			
			if	user.is_staff:
				managerFabricList = Fabric.objects.filter(fabricinformation__isnull = False, category__in = categoryList)
				fabricList = Fabric.objects.filter(fabricinformation__isnull = True, user = user, category__in = categoryList)
			else:
				managerFabricList = Fabric.objects.filter(fabricinformation__isnull = False, category__in = categoryList, valid = valid)
				fabricList = Fabric.objects.filter(fabricinformation__isnull = True, user = user, category__in = categoryList, valid = valid)
			
		elif level == '2':
			supercategory = FabricCategory.objects.get(id = uppercategory)
			categoryList = FabricCategory.objects.filter(supercategory = supercategory)
			fabricList = Fabric.objects.filter(fabricinformation__isnull = False, category__in = categoryList)
			
			if	user.is_staff:
				managerFabricList = Fabric.objects.filter(fabricinformation__isnull = False, category__in = categoryList)
				fabricList = Fabric.objects.filter(fabricinformation__isnull = True, user = user, category__in = categoryList)
			else:
				managerFabricList = Fabric.objects.filter(fabricinformation__isnull = False, category__in = categoryList, valid = valid)
				fabricList = Fabric.objects.filter(fabricinformation__isnull = True, user = user, category__in = categoryList, valid = valid)
				
		else:
			category = FabricCategory.objects.get(id = categoryId)
			if	user.is_staff:
				managerFabricList = Fabric.objects.filter(fabricinformation__isnull = False, category = category)
				fabricList = Fabric.objects.filter(fabricinformation__isnull = True, user = user, category = category)
			else:
				managerFabricList = Fabric.objects.filter(fabricinformation__isnull = False, category = category, valid = valid)
				fabricList = Fabric.objects.filter(fabricinformation__isnull = True, user = user, category = category, valid = valid)
		
		'''
		if	user.is_staff:
			managerFabricList = Fabric.objects.filter(fabricinformation__isnull = False, category = category)
			fabricList = Fabric.objects.filter(fabricinformation__isnull = True, user = user, category = category)
		else:
			managerFabricList = Fabric.objects.filter(fabricinformation__isnull = False, category = category, valid = valid)
			fabricList = Fabric.objects.filter(fabricinformation__isnull = True, user = user, category = category, valid = valid)
		'''
		if settings.ACCESS_CONTROL_BY_CLIENT_GROUP and user.is_authenticated() and not user.userprofile.userType > 1:
			managerFabricList = managerFabricList.filter(Q(allowed_groups__isnull = True) | Q(allowed_groups = user.userprofile.client_group)).distinct()
		if settings.ACCESS_CONTROL_BY_CLIENT_GROUP and user.is_authenticated() and not user.userprofile.userType > 1:
			fabricList = fabricList.filter(Q(allowed_groups__isnull = True) | Q(allowed_groups = user.userprofile.client_group)).distinct()
		
		variables = {'fabricList': fabricList, 'managerFabricList': managerFabricList, 'user':user}
		return render_to_response('xml/fabriclist.xml', RequestContext(request, variables))
	
	
	else:
		if level == '1':
			supersupercategory = FabricCategory.objects.get(id = uppercategory)
			supercategory_list = FabricCategory.objects.filter(supercategory = supersupercategory)
			categoryList = FabricCategory.objects.filter(supercategory__in = supercategory_list)
			managerFabricList = Fabric.objects.filter(fabricinformation__isnull = False, category__in = categoryList, valid = valid)
		elif level == '2':
			supercategory = FabricCategory.objects.get(id = uppercategory)
			categoryList = FabricCategory.objects.filter(supercategory = supercategory)
			managerFabricList = Fabric.objects.filter(fabricinformation__isnull = False, category__in = categoryList, valid = valid)
		else:
			category = FabricCategory.objects.get(id = categoryId)
			managerFabricList = Fabric.objects.filter(fabricinformation__isnull = False, category = category, valid = valid)
			
		if settings.ACCESS_CONTROL_BY_CLIENT_GROUP and user.is_authenticated() and not user.userprofile.userType > 1:
			managerFabricList = managerFabricList.filter(Q(allowed_groups__isnull = True) | Q(allowed_groups = user.userprofile.client_group)).distinct()
		
		variables = {'managerFabricList': managerFabricList, 'user':user}
		return render_to_response('xml/fabriclist.xml', RequestContext(request, variables))
	

## get Fabric list
# Return: xml
def getFabricListManager(request):
	try:
		categoryId = int(request.POST['categoryId'])
		level = request.POST['level']
		uppercategory = request.POST.get('uppercategory', '')
	except:
		raise Http404

	user = request.user
	#fabricList = Fabric.objects.filter(valid = True, fabricinformation__isnull = False, category = category)
	#no matter valid (all valid include False, True)
	if level == '1':
		supersupercategory = FabricCategory.objects.get(id = uppercategory)
		supercategory_list = FabricCategory.objects.filter(supercategory = supersupercategory)
		categoryList = FabricCategory.objects.filter(supercategory__in = supercategory_list)
		fabricList = Fabric.objects.filter(fabricinformation__isnull = False, category__in = categoryList)
	elif level == '2':
		supercategory = FabricCategory.objects.get(id = uppercategory)
		categoryList = FabricCategory.objects.filter(supercategory = supercategory)
		fabricList = Fabric.objects.filter(fabricinformation__isnull = False, category__in = categoryList)
	else:
		category = FabricCategory.objects.get(id = categoryId)
		fabricList = Fabric.objects.filter(fabricinformation__isnull = False, category = category)
	if settings.ACCESS_CONTROL_BY_CLIENT_GROUP and user.is_authenticated() and not user.userprofile.userType > 1:
		fabricList = fabricList.filter(Q(allowed_groups__isnull = True) | Q(allowed_groups = user.userprofile.client_group)).distinct()
	
	variables = {'fabricList': fabricList}
	return render_to_response('xml/fabriclist.xml', RequestContext(request, variables))

## create Fabric
# Return: json - {success: True/False, [id: <created_fabric_id>]}
@csrf_exempt
def createFabric(request):
	valid = request.GET['Visible'].lower() == 'true' if request.POST.has_key('Visible') else False # Default = False
	name = request.FILES['qqfile'].name
	try:
		categoryId = request.GET['CID']
		category = FabricCategory.objects.get(id = categoryId)
	except ObjectDoesNotExist:
		variables = {'success': False, 'reason': 'NoCategory'}
		return HttpResponse(json.dumps(variables), mimetype='application/json')
		
	user = request.user
	if user.is_anonymous():
		variables = {'success': False, 'reason': 'Anonymous'}
		return HttpResponse(json.dumps(variables), mimetype='application/json')
	try:
		orderValue = Fabric.objects.filter(valid = True, category = category, user = request.user).latest().orderValue + 1
	except:
		orderValue = 0;
	
	fabric = Fabric(name = name, valid = valid, user = user, category = category, orderValue = orderValue)
	fabric.save()
	
	IMAGE_EXTENSION = os.path.splitext(name)[-1]
	
	fabricImage = request.FILES['qqfile']
	image_filename = 'data/fabric_images/' + str(fabric.id/10000) + '/' + str(fabric.id) + IMAGE_EXTENSION
	fabric.image.save(image_filename, ContentFile(fabricImage.read()))
	
	img = Image.open(StringIO(fabric.image.read()))
	
	try:
		fabric.dpi = img.info['dpi'][0]
	except KeyError:
		pass
	
	fabric.width, fabric.height = img.size
	
	THUMBNAIL_SIZE = (115, 115)
	IMAGE_TYPE = imghdr.what(fabric.image.path)
	
	img.thumbnail(THUMBNAIL_SIZE, Image.ANTIALIAS)
	temp_handle = StringIO()
	img.save(temp_handle, IMAGE_TYPE)
	temp_handle.seek(0)
	thumb_filename = 'data/fabric_thumbs/' + str(fabric.id/10000) + '/' + str(fabric.id) + IMAGE_EXTENSION
	fabric.thumb.save(thumb_filename, ContentFile(temp_handle.read()))
	
	thum_url = settings.MEDIA_URL + image_filename
	responsePath = settings.MEDIA_URL + thumb_filename

	variables = {'success': True, 'id': fabric.id, 'filepath': responsePath, 'imgWidth':fabric.width, 'imgHeight':fabric.height, 'dpi':fabric.dpi, 'thum_url':thum_url, 'name':name}

	return HttpResponse(json.dumps(variables))	

@csrf_exempt	
def createProductFabric(request):
	try:		
		userId = int(request.POST['UID'])
		productId = int(request.POST['PID'])
		layerName = request.POST['LayerName']
		layerIndex = int(request.POST['LayerIndex'])
		groupIndex = int(request.POST['GroupIndex'])
		grids = request.POST['Grids']
		fabricImage = request.FILES['FabricImage']
		fabricThumb = request.FILES['FabricThumb']
		fabricMask = request.FILES['FabricMask']
		dpi = request.POST['DPI']
		width = request.POST['Width']
		height = request.POST['Height']
	except:
		raise Http404
	
	try:
		product = Product.objects.get(id = productId)
		user = User.objects.get(id = userId)
	except ObjectDoesNotExist:
		raise Http404
	
	belonging= createBelongingToProduct(product, layerName, layerIndex, groupIndex, grids)
	orderValue = 0
	
	valid = request.POST['Visible'].lower() == 'true' if request.POST.has_key('Visible') else True
	
	fabric = Fabric(name = layerName, valid = valid, user = user, category = None, orderValue = orderValue, belonging = belonging, dpi = dpi, width = width, height = height)
	fabric.save()	
	
	# Fabric Image Uploading
	filename = 'data/fabric_images/' + str(fabric.id/10000) + '/' + str(fabric.id) + '.jpg'
	image_content = ContentFile(fabricImage.read())
	fabric.image.save(filename, image_content)
	
	# Fabric Thumb Uploading
	filename = 'data/fabric_thumbs/' + str(fabric.id/10000) + '/' + str(fabric.id) + '.jpg'
	thumb_content = ContentFile(fabricThumb.read())
	fabric.thumb.save(filename, thumb_content)
	
	# Fabric Mask Uploading
	filename = 'data/fabric_masks/' + str(fabric.id/10000) + '/' + str(fabric.id) + '.png'
	mask_content = ContentFile(fabricMask.read())	
	belonging.mask.save(filename, mask_content)
	
	variables = {'success': True, 'id': fabric.id}
	return HttpResponse(json.dumps(variables))

@user_passes_test(admin_check)
def createManagerFabric(request):
	try:
		name = request.POST['name']
		categoryId = int(request.POST['cid'])
		
		code = request.POST['code']
		weight = request.POST['weight']
		width = request.POST['width']
		composition = request.POST['composition']
		price = request.POST['price']
		oneRepeatSize = request.POST['size']
		text = request.POST['text']
		
		oneRepeatImage = request.POST['onerptimg'].lower()
		detailImages = request.POST['detailimg'].lower()
		
		strLaundryTags = request.POST['laundryTags']
		str_allowed_group_ids = request.POST['allowed_group_ids']
		
		valid = request.POST['Visible'].lower() == 'true' if request.POST.has_key('Visible') else False #Default = False
	except:
		raise Http404
	
	try:
		fid = request.POST['fid']
		origin_fabric = Fabric.objects.get(id = fid)
	except:
		origin_fabric = None
	
	try:
		category = FabricCategory.objects.get(id = categoryId)
	except ObjectDoesNotExist:
		raise Http404
	
	try:
		#orderValue = Fabric.objects.filter(valid = True, fabricinformation__isnull = False, category = category).latest().orderValue + 1
		#no matter valid (all valid include False, True)
		orderValue = Fabric.objects.filter(fabricinformation__isnull = False, category = category).latest().orderValue + 1
	except ObjectDoesNotExist:
		orderValue = 0
	
	fabric = Fabric(name = name, user = request.user, category = category, orderValue = orderValue, valid = valid)
	fabric.save()
	
	THUMBNAIL_SIZE = (115, 115)
	
	IMAGE_PATH = media_url2path(oneRepeatImage)
	IMAGE_FILENAME = os.path.split(IMAGE_PATH)[-1]
	IMAGE_EXTENSION = os.path.splitext(IMAGE_FILENAME)[-1][1:]
	IMAGE_TYPE = imghdr.what(IMAGE_PATH)
	
	imgObj = Image.open(IMAGE_PATH)
	
	try:
		fabric.dpi = imgObj.info['dpi'][0]
	except KeyError:
		pass
	
	fabric.width, fabric.height = imgObj.size
	
	temp_handle = StringIO()
	imgObj.save(temp_handle, IMAGE_TYPE)
	temp_handle.seek(0)
	fabric.image.save('data/fabric_images/%s/%s.%s' % (str(fabric.id/10000), str(fabric.id), IMAGE_EXTENSION), ContentFile(temp_handle.read()), save = False)
	
	imgObj.thumbnail(THUMBNAIL_SIZE, Image.ANTIALIAS)
	temp_handle.truncate(0)
	imgObj.save(temp_handle, IMAGE_TYPE)
	temp_handle.seek(0)
	fabric.thumb.save('data/fabric_thumbs/%s/%s.%s' % (str(fabric.id/10000), str(fabric.id), IMAGE_EXTENSION), ContentFile(temp_handle.read()))
	
	detailImageURLList = detailImages.split(';')
	if not '' in detailImageURLList:
		for index, detailImageURL in enumerate(detailImageURLList):
			IMAGE_PATH = media_url2path(detailImageURL)
			IMAGE_FILENAME = os.path.split(IMAGE_PATH)[-1]
			IMAGE_TYPE = imghdr.what(IMAGE_PATH)
			
			fabricDetail = DetailImage(fabric = fabric)
			
			imgObj = Image.open(IMAGE_PATH)
			
			temp_handle.truncate(0)
			imgObj.save(temp_handle, IMAGE_TYPE)
			temp_handle.seek(0)
			fabricDetail.image.save('data/fabric_details/%s/%s/%s' % (str(fabric.id/10000), str(fabric.id), IMAGE_FILENAME), ContentFile(temp_handle.read()), save = False)
			
			imgObj.thumbnail(THUMBNAIL_SIZE, Image.ANTIALIAS)
			temp_handle.truncate(0)
			imgObj.save(temp_handle, IMAGE_TYPE)
			temp_handle.seek(0)
			fabricDetail.thumb.save('data/fabric_details/%s/%s/thumb_%s' % (str(fabric.id/10000), str(fabric.id), IMAGE_FILENAME), ContentFile(temp_handle.read()))
	
	information = FabricInformation(
		fabric = fabric,
		code = code,
		weight = weight,
		width = width,
		composition = composition,
		price = price,
		oneRepeatSize = oneRepeatSize,
		text = text,
	)
	information.save()
	
	laundrytags = information.laundrytags
	for i, tag in enumerate(strLaundryTags.split(';')):
		laundrytags.__dict__['tag%s' % str(i + 1)] = True if tag == '1' else False
	laundrytags.save()
	
	fabric.allowed_groups.clear()
	allowed_group_ids = str_allowed_group_ids.split('-')
	for clientGroup in ClientGroup.objects.filter(id__in = [allowed for allowed in allowed_group_ids if allowed]):
		access_through = Access_to_fabric(client_group = clientGroup, fabric = fabric)
		access_through.save()
	
	# if modifying
	if origin_fabric:
		fabric.orderValue = origin_fabric.orderValue
		fabric.save()
		origin_fabric.delete()
	
	variables = {'success': True, 'id': fabric.id}
	return HttpResponse(json.dumps(variables))

def getFabricInformation(request):
	try:
		fabricId = request.POST['fid']
		fabric = Fabric.objects.filter(fabricinformation__isnull = False, id = fabricId)[0]
	except:
		raise Http404
	
	strLaundrytags = ''
	for i in range(1, 8):
		tag = '1' if fabric.fabricinformation.laundrytags.__dict__['tag%s' % str(i)] else '0'
		strLaundrytags += tag
	
	allowed_group_ids = '-'.join([str(clientGroup.id) for clientGroup in fabric.allowed_groups.all()])
	
	variables = {'fabric': fabric, 'laundrytags': strLaundrytags, 'allowed_group_ids': allowed_group_ids}
	return render_to_response('xml/fabricinformation.xml', RequestContext(request, variables))

def createBelongingToProduct(product, layerName, layerIndex, groupIndex, grids):
	belonging = BelongingToProduct(product = product, layerName = layerName, layerIndex = layerIndex, groupIndex = groupIndex, grids =grids)
	belonging.save()
	return belonging

@csrf_exempt
@login_required
def uploadTempFabricImage(request):
	# return object for json
	response = {}
	
	if not request.FILES.has_key('qqfile'):
		# no file
		response = {'success': False, 'reason': "NoFile"}
	else:		
		# get size limit
		if request.GET.has_key('imgSizeLimit'):
			tempSizeLimit = request.GET['imgSizeLimit']
			imgSizeLimit = (int(tempSizeLimit.split('x')[0]), int(tempSizeLimit.split('x')[1]))
		else:
			imgSizeLimit = (2560, 1440)
			
		# handle uploaded file
		try:
			imgUploadResult = handleUploadedImg(request, 'qqfile', 'data/fabric_temps/' + str(request.user.id) + '/', imgSizeLimit)
		except UploadedImgFileError as e:
			# exception handling for uploaded image file error
			response = {'success':False, 'reason':e.reason}
			return HttpResponse(json.dumps(response))
			

		# return success message
		response = {'success':True, 'filepath':settings.MEDIA_URL+imgUploadResult['path'], 'imgWidth': str(imgUploadResult['size'][0]), 'imgHeight': str(imgUploadResult['size'][1])}
	
	# return reponse dictionary as json type
	return HttpResponse(json.dumps(response))

def deleteFabric(request):
	try:
		fabricId = int(request.POST['fid'])
	except:
		raise Http404
	
	try:
		fabric = Fabric.objects.get(id = fabricId)
	except ObjectDoesNotExist:
		variables = {'success': False, 'reason': 'DoesNotExist'}
		return HttpResponse(json.dumps(variables), mimetype='application/json')
	
	fabric.delete()
	
	variables = {'success': True}
	return HttpResponse(json.dumps(variables), mimetype='application/json')
	
def changeFabricOrdering(request):
	try:
		srcFabricId = int(request.POST['srcfid'])
		dstFabricId = int(request.POST['dstfid'])
		
		srcFabric = Fabric.objects.get(id = srcFabricId)
	except:
		raise Http404
	
	try:
		dstFabric = Fabric.objects.get(id = dstFabricId)
		goingForward = srcFabric.orderValue > dstFabric.orderValue
		lowerBoundary = min(srcFabric.orderValue, dstFabric.orderValue)
		upperBoundary = max(srcFabric.orderValue, dstFabric.orderValue)
	except ObjectDoesNotExist:
		dstFabric = None
		goingForward = False
		lowerBoundary = srcFabric.orderValue
		upperBoundary = None
	
	info_isnull = not hasattr(srcFabric, 'fabricinformation')
	
	siblingFabrics = Fabric.objects.filter(category = srcFabric.category, fabricinformation__isnull = info_isnull)
	
	if dstFabric:
		latest = None
		siblingFabrics = siblingFabrics.filter(orderValue__gt = lowerBoundary, orderValue__lt = upperBoundary)
	else:
		latest = siblingFabrics.latest().orderValue
		siblingFabrics = siblingFabrics.filter(orderValue__gt = lowerBoundary)
	
	if goingForward:
		srcFabric.orderValue = dstFabric.orderValue
		dstFabric.orderValue += 1
		addToSiblingsOrder = 1
	else:
		srcFabric.orderValue = (dstFabric.orderValue - 1) if dstFabric else latest
		addToSiblingsOrder = -1
	
	for fabric in siblingFabrics:
		fabric.orderValue += addToSiblingsOrder
		fabric.save()
	
	srcFabric.save()
	if dstFabric:
		dstFabric.save()
	
	variables = {'success': True}
	return HttpResponse(json.dumps(variables), mimetype='application/json')