# -*- coding: utf-8 -*-
import base64
import json

from PIL import Image
from StringIO import StringIO

from django.core.files.base import ContentFile
from django.views.decorators.csrf import csrf_exempt
from django.views.generic import TemplateView, ListView
from django.http.response import HttpResponse
from core.views import AdminRequiredMixin, page_calc
from simulation.models import OptionMainCategory, OptionSubCategory, Option


class OptionView(AdminRequiredMixin, TemplateView):
	template_name = 'simulation/option/manage_option.html'
	
	def get_context_data(self, **kwargs):
		context = super(OptionView, self).get_context_data(**kwargs)

		context['main_category_list'] = OptionMainCategory.objects.filter(visible=True).order_by('id')

		first_main_category = OptionMainCategory.objects.filter(visible=True).first()
		context['sub_category_list'] = OptionSubCategory.objects.filter(
			main_category=first_main_category,
			visible=True
		).order_by('id')

		first_sub_category = OptionSubCategory.objects.filter(main_category=first_main_category, visible=True).first()
		context['option_list'] = Option.objects.filter(sub_category=first_sub_category, visible=True).order_by('id')
		
		context['selectedCategory'] = 'design'
		context['selectedSubCategory'] = 'option'

		return context

@csrf_exempt
def OptionSubCategoryList(request):
	main_category_id = request.POST.get('main_category')
	categories = []

	sub_category_list = OptionSubCategory.objects.filter(main_category_id = main_category_id, visible=True).order_by('id')
	for sub_category in sub_category_list:
		temp = {
			'id': sub_category.id,
			'name': sub_category.name,
			'max_discount_rate': sub_category.maximum_discount_rate
		}
		categories.append(temp)

	context = {'categories': categories}

	return HttpResponse(json.dumps(context), content_type="application/json")

@csrf_exempt
def OptionList(request):
	sub_category_id = request.POST.get('sub_category')
	options = []

	option_list = Option.objects.filter(sub_category_id = sub_category_id, visible=True).order_by('id')
	for option in option_list:
		temp = {
			'id': option.id,
			'name': option.name,
			'price': option.price,
			'thumb': option.thumb.url
		}
		options.append(temp)

	context = {'options': options}
	return HttpResponse(json.dumps(context), content_type="application/json")

@csrf_exempt
def AddOption(request):
	sub_category_id = request.POST.get('sub_category')
	name = request.POST.get('optionName')
	price = request.POST.get('optionPrice')
	thumb = request.FILES['file-image-thumb']
	front = request.FILES['file-image-front'] if 'file-image-front' in request.FILES else ''
	back = request.FILES['file-image-back'] if 'file-image-back' in request.FILES else ''

	sub_category = OptionSubCategory.objects.get(id=sub_category_id)

	newOption = Option.objects.create(
		sub_category=sub_category,
		name=name,
		price=price,
		visible=True
	)
	newOption.thumb = thumb

	if not front == '':
		front_img = image_composite(front)
		newOption.front_image.save('front.png', ContentFile(front_img.read()))
		front_img.close()

	if not back == '':
		back_img = image_composite(back)
		newOption.back_image.save('back.png', ContentFile(back_img.read()))
		back_img.close()

	context = {
		'id': newOption.id,
		'thumb': newOption.thumb.url,
		'name': newOption.name,
		'price': newOption.price
	}
	return HttpResponse(json.dumps(context), content_type="application/json")


@csrf_exempt
def DeleteOption(request):
	option_id = request.POST.get('option')
	delete_option = Option.objects.get(id=option_id)
	delete_option.visible = False
	delete_option.save()

	deleteOptionsForNonContractedOrders(delete_option)

	context = {'id': delete_option.id}
	return HttpResponse(json.dumps(context), content_type="application/json")


def image_composite(option_img):
	# thumbnail

	img = Image.open(option_img)
	origin_width, origin_height = img.size

	resize_width = 200
	new_size = (resize_width, resize_width * origin_height / origin_width)

	img.thumbnail(new_size, Image.ANTIALIAS)

	# composite
	#composite_width = (couple_original_width * resize_width) / fitting_original_width
	composite_width = 351
	composite_height = new_size[1]

	couple_image = Image.new('RGBA', (composite_width, composite_height))
	couple_image.paste(img, (0, 0))
	couple_image.paste(img, (155, 0))

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

	composite_img = ContentFile(temp_handle.read())
	temp_handle.close()
	couple_image.close()
	img.close()

	return composite_img

@csrf_exempt
def AddMainCategory(request):
	new_name = request.POST.get('new_name')

	newMainCategory = OptionMainCategory.objects.create(name=new_name, visible=True)

	context = {
		'id': newMainCategory.id,
		'name': newMainCategory.name
	}
	return HttpResponse(json.dumps(context), content_type="application/json")

@csrf_exempt
def AddSubCategory(request):
	main_category_id = request.POST.get('main_category')
	new_name = request.POST.get('new_name')
	discount_rate = request.POST.get('discount_rate')

	main_category = OptionMainCategory.objects.get(id=main_category_id)
	newSubCategory = OptionSubCategory.objects.create(
		main_category = main_category,
		name = new_name,
		maximum_discount_rate = discount_rate,
		visible = True
	)

	context = {
		'id': newSubCategory.id,
		'name': newSubCategory.name,
		'max_discount_rate': newSubCategory.maximum_discount_rate
	}
	return HttpResponse(json.dumps(context), content_type="application/json")


@csrf_exempt
def DeleteMainCategory(request):
	delete_category_id = request.POST.get('deleteCategory')
	delete_category = OptionMainCategory.objects.get(id=delete_category_id)
	delete_category.visible = False
	delete_category.save()

	for sub_category in delete_category.optionsubcategory_set.all():
		for option in sub_category.option_set.all():
			deleteOptionsForNonContractedOrders(option)

	context = {'id': delete_category.id}
	return HttpResponse(json.dumps(context), content_type="application/json")

@csrf_exempt
def DeleteSubCategory(request):
	delete_category_id = request.POST.get('deleteCategory')
	delete_category = OptionSubCategory.objects.get(id=delete_category_id)
	delete_category.visible = False
	delete_category.save()

	for option in delete_category.option_set.all():
		deleteOptionsForNonContractedOrders(option)

	context = {'id': delete_category.id}
	return HttpResponse(json.dumps(context), content_type="application/json")

def deleteOptionsForNonContractedOrders(option):
	for order in option.ordercontract_set.all():
		if order.order_status < 5:
			order.optionquantity_set.get(option=option).delete()