# Create your views here.
from django.template import Context, RequestContext, loader
from django.db.models import Q
from django.http import HttpResponse, Http404
from django.shortcuts import get_list_or_404, render_to_response

from forms import MorfaCElement
from django.forms.formsets import formset_factory

from smadrill.models import Word


def formToQuery(formdict):
	# TODO: need a bit better logic somewhere that removes semtypes and
	# forms depending. ex. Pron and semtype, pronouns have no semtype so
	# nothing will come up.


	keytokey = {
		'wordstring': 'lemma__contains', # TODO: wildcard?
		'tagstr': 'form__tag__id',
		'semtype': 'semtype__id',
		'sample': None,
		'additionals': None,
	}
	
	qkwargs = {'language': 'sma'}
	for item, value in formdict.items():
		value = value.strip()
		nkey = keytokey[item]

		if nkey and value:
			if value != 'None':
				qkwargs[nkey] = value
	print qkwargs
	return qkwargs


def process(request):
	""" Ajax call for fetching lemmas, forms, returns json list of first 20
		
		If tag is supplied, from Form, otherwise from Word
	"""
	c = {}
	template = "morfac_lab_index.html"
	# {'sample': u'', 'wordstring': u'', 'tagstr': u'108', 'additionals': u'', 'semtype': u'2'}
	
	# TODO: remove element.
	initial = False
	if request.method == 'POST':
		formset = formset_factory(MorfaCElement, extra=1)
		data = formset(request.POST)
		add_form = False

		if data.is_valid():
			initial = []
			if 'add' in request.POST:
				add_form = True

			for form in data.forms:
				if form.is_valid():
					initl = form.cleaned_data
					qkwargs = formToQuery(initl)
					tagstr = initl['tagstr']
					semtype = initl['semtype']

					if tagstr.strip():
						if tagstr in ['None', None]:
							tagstr = None

					if semtype.strip():
						if semtype in ['None', None]:
							semtype = None

					# If no tag and no semtype, no filter here
					if tagstr or semtype:
						additionals = Word.objects.filter(**qkwargs)

						if additionals.count() > 0:
							sample = additionals.order_by('?')[0]

							if tagstr:
								sample = sample.form_set.filter(tag__id=tagstr)[0]
								sample = sample.fullform
							else:
								sample = sample.lemma


							if additionals.count() > 14:
								additionals = additionals[0:15]
						else:
							sample = ''
					else:
						additionals = ''
						sample = ''

						if initl['wordstring']:
							sample = initl['wordstring']

					
					initl['additionals'] = [a.lemma for a in additionals]
					initl['sample'] = sample

					initial.append(initl)

		if initial:
			if add_form:
				extra_count = 1
			else:
				extra_count = 0
			formset = formset_factory(MorfaCElement, extra=extra_count)(initial=initial)
			c['elements'] = formset
	
	return render_to_response('morfac_lab_index.html',
						      c,
							  context_instance=RequestContext(request))

def index(request):
	c = {}
	template = "morfac_lab_index.html"
	

	formset = formset_factory(MorfaCElement, extra=1)()

	c['elements'] = formset
	
	return render_to_response(template,
							  c,
							  context_instance=RequestContext(request))

