from django.conf import settings
from django.dispatch import receiver
from django.db.models.signals import post_save
from django.contrib.contenttypes.models import ContentType

from . import models, tasks, utils


@receiver(post_save, sender=models.Video)
def post_save_video(sender, instance, created, **kwargs):
    if instance.status == models.PROGRESS and instance.local_file and instance.slug:
        tasks.send_video_to_s3.apply_async((instance.id,))


@receiver(post_save, sender=models.Playlist)
def post_save_playlist(sender, instance, created, **kwargs):
    if not instance.json or not instance.mrss:
        instance.json = f'{settings.DOMAIN_NAME}/api/playlist/{instance.id}/'
        instance.mrss = f'{settings.DOMAIN_NAME}/api/playlist/{instance.id}/mrss'
        instance.save()


@receiver(post_save, sender=models.TagToObject)
def post_save_tags(sender, instance, created, **kwargs):
    if created:
        playlist_content_type = ContentType.objects.get_for_model(models.Playlist)
        if instance.content_type == playlist_content_type:
            playlist = models.Playlist.objects.get(id=instance.object_id)
            if playlist.type == models.DYNAMIC:
                utils.add_video_to_new_playlist(playlist)