#-*- coding: utf-8 -*-
from __future__ import division
from django.views.decorators.csrf import csrf_exempt, csrf_protect
from django.http import HttpResponse, Http404
from xml.etree.ElementTree import Element, ElementTree, SubElement, parse
from simulation.models import *
from django.core.files.base import ContentFile
from cStringIO import StringIO
from django.conf import settings
from PIL import Image

import os
import shutil



def convertFabricCodeFormat(code):
	return '%0*d' % (3, int(code) + 1)


def readXml(tex3dXml):
	product = Product()
	product.save()
	product.xml.save(tex3dXml.name, ContentFile(tex3dXml.read()))

	with product.xml as xml:
		doc = parse(xml)

	root = doc.getroot()

	xml_product = root.find("ProductList")[0]
	product.name = root.find("Coordi").get("name").split(".")[0]
	product.code = xml_product.attrib["cloth_code"]
	product.product_type = ProductType.objects.get(name__contains=xml_product.attrib["name"].lower())
	product.season = root.find("Coordi").get("season")
	product.style = root.find("Coordi").get("style")
	product.user = User.objects.get(username=root.find("Coordi").get("id"))
	product.main_fabric_group = root.find("Coordi").get("mainfabric")
	product.save()

	main_fabric_group_index = int(product.main_fabric_group)
	xml_fabric_group = root.find("FabricGroupList")[main_fabric_group_index]
	for xml_fabric in xml_fabric_group.iter("Fabric"):
		main_fabric = MainFabric(product=product)
		fabric_code = xml_fabric.attrib["fabric_index"]
		main_fabric.index = convertFabricCodeFormat(fabric_code)
		main_fabric.name = xml_fabric.attrib["name"]
		main_fabric.save()


def saveFabric(fabricThumbs, product):
	for fabric in enumerate(fabricThumbs):
		fabricFile = fabric[1].name
		group_code = fabricFile[0:2]
		fabric_code = fabricFile[2:4]

		if group_code == product.main_fabric_group:
			m_fabric = MainFabric.objects.get(product=product, index=convertFabricCodeFormat(fabric_code))
			m_fabric.image.save('main_fabric/' + fabricFile, ContentFile(fabric[1].read()))
		else:
			pass


def saveTxm(txm_file, product):
	product.txm.save('txm/' + txm_file.name, ContentFile(txm_file.read()))


def saveGrid(gridImages, product):
	for grid in enumerate(gridImages):
		grid_name = grid[1].name
		fabric_code = grid_name[2:4]

		main_fabric = MainFabric.objects.get(product=product, index=convertFabricCodeFormat(fabric_code))

		grid_object = Grid(fabric=main_fabric)
		grid_object.save()

		detail_index = grid_name[5:6]
		if detail_index == '0':
			grid_object.side = 'front'
		else:
			grid_object.side = 'back'

		grid_object.image.save('grid/' + grid_name, ContentFile(grid[1].read()))
		grid_object.save()

#
# def setSelectedProduct(product):
#
# 	selected_product = SelectedProduct(product=product, main_fabric=MainFabric.objects.get(product=product, index="00"))
# 	selected_product.save()


def compositeGrid(grids, thumb_size):
	idx = 0
	composite_img = ''
	for grid in grids:
		if idx == 0:
			composite_img = Image.open(grid.image)
		else:
			img = Image.open(grid.image)
			with composite_img as c:
				composite_img = Image.alpha_composite(c, img)
				grid.image.close()
			img.close()
		idx = idx + 1

	composite_img.thumbnail(thumb_size, Image.ANTIALIAS)

	temp_handle = StringIO()
	composite_img.save(temp_handle, 'PNG')
	temp_handle.seek(0)

	thumbImage = ContentFile(temp_handle.read())

	temp_handle.close()
	composite_img.close()

	return thumbImage


def createProductThumbnail(product):
	main_fabrics = MainFabric.objects.filter(product=product)
	IMAGE_EXTENSION = '.png'

	original_width = Grid.objects.filter(fabric__product=product).first().image.width
	original_height = Grid.objects.filter(fabric__product=product).first().image.height

	# resize 할 width 값 지정
	#fitting_resize_width = original_width
	fitting_resize_width = 500
	product_thumb_resize_width = 300

	fitting_thumb_size = (fitting_resize_width, (fitting_resize_width * original_height / original_width))
	product_thumb_size = (product_thumb_resize_width, (product_thumb_resize_width * original_height / original_width))

	resize_ratio = fitting_thumb_size[0] / original_width

	for main_fabric in main_fabrics:
		front_grids = Grid.objects.filter(fabric=main_fabric, side='front').order_by('id')
		back_grids = Grid.objects.filter(fabric=main_fabric, side='back').order_by('id')

		front_image = compositeGrid(front_grids, fitting_thumb_size)
		image_filename = 'mapping/front/' + str(main_fabric.id) + IMAGE_EXTENSION
		main_fabric.front_mapping_image.save(image_filename, ContentFile(front_image.read()))
		front_image.close()

		crop_thumb = cropProductThumb(product, main_fabric.front_mapping_image, resize_ratio, product_thumb_size)
		image_filename = 'mapping/thumb/' + str(main_fabric.id) + IMAGE_EXTENSION
		main_fabric.mapping_thumb.save(image_filename, ContentFile(crop_thumb.read()))
		crop_thumb.close()

		back_image = compositeGrid(back_grids, fitting_thumb_size)
		image_filename = 'mapping/back/' + str(main_fabric.id) + IMAGE_EXTENSION
		main_fabric.back_mapping_image.save(image_filename, ContentFile(back_image.read()))
		back_image.close()

def cropProductThumb(product, img, ratio, thumb_size):
	crop_img = Image.open(img)
	product_type = product.product_type.name

	crop_size = 0
	if product_type == 'skirt' or product_type == 'pants':
		crop_size = (int(round(100 * ratio)), int(round(1000 * ratio)), int(round(900 * ratio)), int(round(1660 * ratio)))
	else:
		crop_size = (int(round(100 * ratio)), int(round(450 * ratio)), int(round(900 * ratio)), int(round(1440 * ratio)))

	crop_img = crop_img.crop(crop_size)
	crop_img.thumbnail(thumb_size, Image.ANTIALIAS)

	temp_handle = StringIO()
	crop_img.save(temp_handle, 'PNG')
	temp_handle.seek(0)

	thumbImage = ContentFile(temp_handle.read())

	temp_handle.close()
	crop_img.close()

	return thumbImage

def deleteGridFile(product_id):
	if os.path.exists(settings.MEDIA_ROOT + '/product/' + str(product_id) + '/grid/'):
		shutil.rmtree(settings.MEDIA_ROOT + '/product/' + str(product_id) + '/grid/')


def getProduct():
	return Product.objects.latest('id')

@csrf_exempt
def uploadProduct(request):
	if request.FILES.has_key('tex3dXml'):
		readXml(request.FILES['tex3dXml'])

	if request.FILES.has_key('FabricThumb'):
		saveFabric(request.FILES.getlist('FabricThumb'), getProduct())

	if request.FILES.has_key('tex3dTxm'):
		saveTxm(request.FILES['tex3dTxm'], getProduct())

	if request.FILES.has_key('GridImages'):
		saveGrid(request.FILES.getlist('GridImages'), getProduct())

	if request.POST.has_key('createEnd'):
		# setSelectedProduct(getProduct())
		createProductThumbnail(getProduct())
		deleteGridFile(getProduct())

	variables = {'success': True}
	return HttpResponse(variables)