from django.db import models
from django.db.models.fields import TextField
from django.contrib.postgres.search import SearchVectorField, SearchVector
from django.contrib.postgres.indexes import GinIndex
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
import uuid
# Create your models here.


#-------------------------------------------------------------------------------
class Publisher(models.Model):
	name = models.CharField(max_length=128)
	shortName = models.CharField(max_length=32, default="")
	crawler = models.CharField(max_length=64, default="")
	type = models.CharField(max_length=32, default='')
	url = models.URLField(default="")
	active = models.BooleanField(default=True)
	country = models.CharField(max_length=32, default='')
	region = models.CharField(max_length=32, default='')
	def __str__(self):
		return self.shortName

	class Meta:
		verbose_name = 'Medio'
		verbose_name_plural = 'Medios'
		ordering = ('name',)

#-------------------------------------------------------------------------------
class Topic(models.Model):
	name = models.CharField(verbose_name='Tema', max_length=256)

	def __str__(self):
		return self.name

	class Meta:
		verbose_name = 'Tema'
		verbose_name_plural = 'Temas'
		ordering = ('name',)
		
#-------------------------------------------------------------------------------
class PostManager(models.Manager):
	def with_documents(self):
		vector = SearchVector('text')
		return self.get_queryset().annotate(document=vector)
		
#-------------------------------------------------------------------------------
class News(models.Model):
	title = models.CharField(max_length=512)
	publisher = models.ForeignKey(Publisher, on_delete=models.CASCADE, default='')
	topic = models.ManyToManyField(Topic, verbose_name='Topic(s)', blank=True)
	topic_raw = models.CharField(max_length=1024, default='')
	date = models.DateTimeField(verbose_name='Publication Date')
	text = TextField(verbose_name='News Text', default='', blank=True)
	url = models.URLField(verbose_name='URL', max_length=512)
	search_vector = SearchVectorField(null=True)
	objects = PostManager()
	
	def save(self, *args, **kwargs):
		super(News, self).save(*args, **kwargs)
		if 'update_fields' not in kwargs or 'search_vector' not in kwargs['update_fields']:
			instance = self._meta.default_manager.with_documents().get(pk=self.pk)
			instance.search_vector = instance.document
			instance.save(update_fields=['search_vector'])

	def __str__(self):
		return self.title

	class Meta:
		verbose_name = 'Noticia'
		verbose_name_plural = 'Noticias'
		ordering = ('date',)
		indexes = [ GinIndex(fields=['search_vector']) ]
#-------------------------------------------------------------------------------
class Search(models.Model):
	user = models.ForeignKey(User, on_delete=models.CASCADE)
	startDate = models.DateTimeField(verbose_name='Start Date')
	endDate = models.DateTimeField(verbose_name='End Date')
	text = models.CharField(max_length=128,blank=True)
	publishers = models.ManyToManyField(Publisher,blank=True)

#-------------------------------------------------------------------------------
class Profile(models.Model):
	user = models.OneToOneField(User, on_delete=models.CASCADE)
	subscriptions = models.ManyToManyField(Publisher)

@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
	if created:
		Profile.objects.create(user=instance)#, subscriptions=Publisher.objects.all())
		print ("profile created")

@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
	instance.profile.save()
	
#-------------------------------------------------------------------------------
class Apikey(models.Model):
	key = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
	user = models.ForeignKey(User, on_delete=models.CASCADE)
	endDate = models.DateTimeField(verbose_name='Expiration date')
	
#-------------------------------------------------------------------------------
class audioTime(models.Model):
	publisher = models.ForeignKey(Publisher, on_delete=models.CASCADE)
	startDate = models.DateTimeField(verbose_name='Start Date')
	endDate = models.DateTimeField(verbose_name='End Date')
	minutes =  models.BigIntegerField(default=0)

