# *coding: utf-8*
import logging,os
from django.db.models import F
from django.core.files.storage import default_storage
from django.db.models import FileField
# Get an instance of a logger
logger = logging.getLogger('django')


def signal_delete_model(sender,**kwargs):
    logger.info("=========================  SIGNAL DELETE  =======================")

def signal_add_photo(sender, **kwargs):
    # Check si la photo contient de la nudité
    if not kwargs['created']: return None
    #
    photo = kwargs['instance']
    #check_nudity_task.delay(photo.picture)
    # TODO : Prevenir tous les followers du user de la photo


def signal_predelete_userlike(sender, **kwargs):
    logger.info("=========================  SIGNAL DELETE USER LIKE =======================")
    userLikeToDelete = kwargs['instance']
    from .models import Post,User
    # Decrement nbLike
    try:
        user = User.objects.get(pk=userLikeToDelete.refUser.id)
        user.nbLike -= 1
        user.save()
        thePost = userLikeToDelete.refPost
        thePost.nbLike -= 1
        thePost.save()
        return None
    except Exception as e:
        logger.info("================================== Impossible DELETE nbLike %s", e)
        return None

def signal_delete_post(sender, **kwargs):
    logger.info("=========================  SIGNAL DELETE POST =======================")
    postToDelete = kwargs['instance']
    try:
        from .models import User
        user = User.objects.get(pk=postToDelete.refUser.id)
        user.nbPost -= 1
        user.save()
        return None
    except Exception as e:
        logger.info("================================== Impossible DELETE POST %s", e)
        return None

def signal_add_postcomment(sender,**kwargs):
    if not kwargs['created']: return None
    postcomment = kwargs['instance']
    from .models import NotificationToSend
    try:
        thePost = postcomment.refPost
        thePost.nbComment +=1
        thePost.save()
        notification = NotificationToSend()
        notification.toUserId = thePost.refUser
        # Prevenir par push l'utilisateur
        userToNotify = thePost.refUser
        if userToNotify.refTown==4:
            notification.message='Un utilisateur a commenté votre post'
        else:
            notification.message='A user had commented your post'
        notification.status=0
        notification.notifyType =0
        notification.save()
        return None
    except Exception as e:
        logger.info("================================== Impossible d'incrementer nbComment %s", e)
        return None

def signal_add_userlike(sender,**kwargs):
    if not kwargs['created']: return None
    userlike = kwargs['instance']
    # increment nbLike sur la table Post
    from .models import User,NotificationToSend
    try:
        user = User.objects.get(pk=userlike.refUser.id)
        user.nbLike += 1
        user.save()
        thePost = userlike.refPost
        thePost.nbLike +=1
        thePost.save()
        # Prevenir par push l'utilisateur
        userToNotify = thePost.refUser
        notification = NotificationToSend()
        notification.toUserId = thePost.refUser
        # Prevenir par push l'utilisateur
        userToNotify = thePost.refUser
        if userToNotify.refTown == 4:
            notification.message = 'Un utilisateur a liké votre post'
        else:
            notification.message = 'A user liked your post'
        notification.status = 0
        notification.notifyType = 0
        notification.save()
        return None
    except Exception as e:
        logger.info("================================== Impossible d'incrementer nbLike %s", e)
        return None


def signal_addvote(sender,**kwargs):
    logger.info("=========================  SIGNAL ADD VOTE =======================")
    if not kwargs['created']: return None
    from .models import PlacesVote,Place
    placevoteInstance = kwargs['instance']
    placeNote = placevoteInstance.refPlace
    # Ok on prend toutes les notes de l'utilisateur
    listeNote = PlacesVote.objects.filter(refPlace=placeNote)
    nbTotal = 0
    noteTotal = 0
    for note in listeNote:
        logger.info("on a note " + str(note.note))
        noteTotal += note.note
        nbTotal += 1
    logger.info("on a finalement Note " + str(noteTotal) + " nb " + str(nbTotal))
    moyenne = noteTotal / nbTotal
    logger.info("moyenne " + str(moyenne))
    placeToUpdate = Place.objects.get(pk=placeNote.id)
    placeToUpdate.noteAverage = moyenne
    placeToUpdate.nbVote = nbTotal
    placeToUpdate.save()
    logger.info("================================================")

def signal_add_message(sender,**kwargs):
    logger.info("=========================  SIGNAL ADD message =======================")
    from .models import Chat, NotificationToSend
    if not kwargs['created']: return None
    chatMessage = kwargs['instance']
    chat =  Chat.objects.get(pk=chatMessage.refChat.id)
    userOne = chat.refUserOne
    userTwo = chat.refUserTwo
    if chatMessage.senderId.id==userOne.id:
        #envoi userTwo
        userToNotify =userTwo
        notification = NotificationToSend()
        notification.toUserId = userToNotify
        if userToNotify.online==False:
            if userToNotify.refTown == 4:
                notification.message = 'Vous avez reçu un nouveau message'
            else:
                notification.message = 'You have received a new message'
            notification.status = 0
            notification.notifyType = 0
            notification.save()
    else:
        # envoi userOne
        userToNotify = userOne
        notification = NotificationToSend()
        notification.toUserId = userToNotify
        if userToNotify.online == False:
            if userToNotify.refTown == 4:
                notification.message = 'Vous avez reçu un nouveau message'
            else:
                notification.message = 'You have received a new message'
            notification.status = 0
            notification.notifyType = 0
            notification.save()

def signal_add_post(sender,**kwargs):
    logger.info("=========================  SIGNAL ADD message =======================")
    from .models import Post,User, NotificationToSend
    if not kwargs['created']: return None
    post = kwargs['instance']
    # préviens julien christophe
    users = User.objects.filter(email="lepitch@agender.fr")
    for user in users:
        if user.id is not post.refUser.id:
            notification = NotificationToSend()
            notification.toUserId = user
            notification.message = 'Un nouveau post doit etre validé'
            notification.status = 0
            notification.notifyType = 0
            notification.save()

