from __future__ import unicode_literals
from django.db import models
# import CsvModel
import csv
import os


class Institute(models.Model):
	name=models.CharField(max_length=200)
	def __str__(self):
		return self.name
	class Meta:
		verbose_name='Institute'
		verbose_name_plural='Institutes'

class Choice(models.Model):
	choice_name = models.CharField(max_length=200)
	institute=models.ForeignKey(Institute, on_delete=models.CASCADE, related_name='choices')
	capacity = models.IntegerField()
	def __str__(self):
		return self.choice_name

# Null_Choice=Choice.objects.create(choice_name="None",capacity=1000)
# Null_Choice.save()

class Applicant(models.Model):
	institute=models.ForeignKey(Institute,on_delete=models.CASCADE,related_name='applicants')
	choices = models.ManyToManyField(Choice, through='Application', related_name='applicants')
	name = models.CharField(max_length=200)
	alloted_choice = models.ManyToManyField(Choice, through='Allocationcl', related_name='alloted_applicant')
	rank = models.IntegerField()
	def __str__(self):
		return self.name
	def ordered_choices(self):  
	#https://stackoverflow.com/questions/934779/django-order-a-model-by-a-many-to-many-field
		"Return a properly ordered set of choices"
		return self.choices.all().order_by('application__priority')

class Application(models.Model):
	applicant = models.ForeignKey(Applicant, on_delete=models.CASCADE)
	choice = models.ForeignKey(Choice, on_delete=models.CASCADE)
	priority = models.IntegerField()
	class Meta:
		# if you have an inline configured in the admin, this will 
		# make the roles order properly 

		ordering = ['priority'] 


class Allocationcl(models.Model):
	choice = models.ForeignKey(Choice, on_delete=models.CASCADE)
	applicant = models.ForeignKey(Applicant, on_delete=models.CASCADE)
	# priority = models.IntegerField()
	class Meta:
		# if you have an inline configured in the admin, this will 
		# make the roles order properly 
		verbose_name='Allocated Choice'
		verbose_name_plural='Allocated Choice'
		ordering = ['applicant__rank']

# class UnivChoice(models.Model):
# ,limit_choices_to={'institute':applicant.institute}
# 	choice=models.ForeignKey(Choice,on_delete=models.CASCADE)
# 	university=models.ForeignKey(University,on_delete=models.CASCADE)
# , limit_choices_to={'university__name':'applicant_university__name'}
# class UnivApp(models.Model):
# 	applicant=models.ForeignKey(Applicant,on_delete=models.CASCADE)
# 	university=models.ForeignKey(University,on_delete=models.CASCADE)
# 	class Meta:
# 		ordering=['applicant__rank']