# -*- 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.core.exceptions import ObjectDoesNotExist
from django.core.files.base import ContentFile
from django.db import IntegrityError
from django.db.models import Count
from cStringIO import StringIO
from django.core.files.uploadedfile import SimpleUploadedFile
from users.models import *
from product.models import *
from fabric.models import *
from simulation.models import *
from PIL import Image, ImageDraw

import json
import sys
import os.path
import settings
import operator
import shlex
import subprocess
import imghdr

## run Simulation
# 1. Insert User ID for foreignKey to the simulation table
# 2. Call runTex3dParam function
#	- id: select id from simulation where user = userId
#	- fn: productId.txf
#	- pt_stc

def runSimulation(request):
	try:
		productId = int(request.POST['PID'])
		fabricIds = request.POST['FIDS']
	except:
		raise Http404
	
	try:
		user = request.user
		product = Product.objects.get(id = productId)
		belongings = BelongingToProduct.objects.filter(product = product).order_by('id')
	except ObjectDoesNotExist:
		raise Http404
	
	using_fabric = fabricIds.split(',')
	filename = str(product.id/10000) + '/' + str(product.id) + '.txd'
	
	i = 0
	patternInfo = ''
	for belong in belongings:
		try:
			fabric = Fabric.objects.get(id = int(using_fabric[i]))
			fabric_fn = str(fabric.id/10000) + '/' + os.path.split(fabric.image.url)[-1]
			i += 1
			patternInfo += fabric_fn + ';' + str(fabric.dpi) + ';' + str(belong.layerIndex) + ';' + belong.grids + ' '
		except ObjectDoesNotExist:
			raise Http404
	
	user = None if user.is_anonymous() else user
	
	cache_str = ' '.join((str(productId), fabricIds))
	if Simulation.objects.filter(cache_str = cache_str).exists():
		if user is not None and user.is_staff:
			for simulation in Simulation.objects.filter(cache_str = cache_str):
				simulation.delete()
		else:
			simulation = Simulation.objects.filter(cache_str = cache_str)[0]
			try:
				simulation_image_url = simulation.image.url
				variables = {'success': True, 'url': simulation.image.url}
				return HttpResponse(json.dumps(variables), mimetype='application/json')
			except:
				simulation.delete()
	
	simulation = Simulation(user = user, cache_str = cache_str)
	simulation.save()
	
	result = runTex3dParam(str(simulation.id), filename, patternInfo)
	
	if result == True:
		sim_path = settings.MEDIA_ROOT + 'data/simulation/' + str(simulation.id) + '.jpg'
		save_path = 'data/simulation/' + str(simulation.id/10000) + '/' + str(simulation.id) + '.jpg'
		
		imgObj = Image.open(sim_path)
		temp_handle = StringIO()
		IMAGE_TYPE = imghdr.what(sim_path)
		imgObj.save(temp_handle, IMAGE_TYPE)
		temp_handle.seek(0)
		suf = SimpleUploadedFile('simulationFiles.jpg', temp_handle.read())
		simulation.image.save(save_path, suf)
		
		os.remove(sim_path)
		
		variables = {'success': True, 'url': simulation.image.url}
	
	else:
		simulation.delete()
		variables = {'success': False}
	
	return HttpResponse(json.dumps(variables), mimetype='application/json')
	
## run Tex3D_Param.exe 
# ID 0(Zoom) FileName Pattern;Layer;GridGroup No.
# 3175 0.txd 15.jpg;0;2,3 10.bmp;2;0,4
def runTex3dParam(sid, fn, pt_etc):
	try:
		save_path = settings.MEDIA_ROOT + 'data/simulation/' + sid + '.jpg'	
		if os.path.exists(save_path):
			os.remove(save_path)

		cmd = settings.MEDIA_ROOT + 'data/webtex3d/Tex3D_Param.exe {i} 0 {f} {p}'.format(i = sid, f = fn, p = pt_etc)
		args = shlex.split(cmd)
		proc = subprocess.Popen(args)
		rtn = proc.communicate()
		
		if not os.path.exists(save_path):
			raise Exception('file not exist')
	except:
		return False
	
	return True
	
## run Tex3D_Sim.exe 
#
def runTex3dSim(request):
	try:
		cmd = 'h:' + settings.MEDIA_ROOT + 'data/webtex3d/Tex3D_Sim.exe'
		args = shlex.split(cmd)
		proc = subprocess.Popen(args)
		variables = {'success': True}
	except:
		variables = {'success': False}
			
	return HttpResponse(json.dumps(variables), mimetype='application/json')
		
def cleanupSimulations(request):
	try:
		for simulation in Simulation.objects.all():
			simulation.delete()
		
		variables = {'success': True}
	except:
		variables = {'success': False}
	
	return HttpResponse(json.dumps(variables), mimetype='application/json')
