from PIL import Image
import re

from django import template
from django.template.defaulttags import register

from django.conf import settings
from django.db.models import Avg

from ..models import Product, User, Vote, Media, Contact
register = template.Library()



# @register.simple_tag
# def model_name(obj):
#     '''
#     Django template filter which returns the verbose name of a model.
#     '''
#     if hasattr(obj, 'model'):
#         obj = obj.model
#
#     return obj._meta.verbose_name.title()
#
#
# @register.simple_tag
# def model_name_plural(obj):
#     '''
#     Django template filter which returns the plural verbose name of a model.
#     '''
#     if hasattr(obj, 'model'):
#         obj = obj.model
#
#     return obj._meta.verbose_name_plural.title()




@register.simple_tag
def field_name(obj, field):
    '''
    Django template filter which returns the verbose name of an object's,
    model's or related manager's field.
    '''
    # if hasattr(obj, 'model'):
    #     obj = obj.model

    return obj._meta.get_field(field).verbose_name




@register.filter
def get_item(dictionary, key):
    return dictionary.get(key)



@register.simple_tag
def get_vote(Product, user):
    if user.groups.filter(name='jury').exists():
        try:
            vote = Vote.objects.get(juryMember=user, product=Product)
        except Vote.DoesNotExist:
            return 'VOTE !'

        return 'VOTE: ' + str(vote.vote)
    return ''

@register.simple_tag
def get_int_vote(Product, user):

    try:
        vote = Vote.objects.get(juryMember=user, product=Product)

    except Vote.DoesNotExist:
        return 0

    return vote.vote

@register.simple_tag
def get_comment(Product, user):

    try:
        vote = Vote.objects.get(juryMember=user, product=Product)

    except Vote.DoesNotExist:
        return 'Here is some space for your comments (not obligatory)'
    if vote.comment=='':
        return 'Here is some space for your comments (not obligatory)'

    return vote.comment


@register.simple_tag
def get_ratio(media):
    path = media.image.url

    try:
         with Image.open(settings.MEDIA_URL + path) as img:
             width, height = img.size

    except FileNotFoundError:
        return 3;


    return str(width/height)



@register.simple_tag
def get_vote_simple(Product, user):
    try:
        vote = Vote.objects.get(juryMember=user, product=Product)

    except Vote.DoesNotExist:
        return '-'

    return str(vote.vote)


@register.simple_tag
def get_avg(Product):
    try:
        votes = Vote.objects.filter(product=Product)

    except Vote.DoesNotExist:
        return '-'

    return votes.aggregate(Avg('vote'))['vote__avg']

@register.simple_tag
def get_countries(Product_list):
    countries = {''}
    for Product in Product_list:

       if not countries.__contains__(Product.country):
           countries.add(Product.country)

    return countries

@register.simple_tag
def get_vote_class(Product, user):

    try:
        Vote.objects.get(juryMember=user, product=Product)

    except Vote.DoesNotExist:
        return 'notvote'

    return 'vote'

@register.simple_tag
def get_sucsess(Product):
    try:
        votes = Vote.objects.filter(product=Product)

    except Vote.DoesNotExist:
        return ''
    if votes.aggregate(Avg('vote'))['vote__avg'] is not None:
        if votes.aggregate(Avg('vote'))['vote__avg'] >= 7:
            return 'table-success'

    return ''

@register.simple_tag
def get_vote_txt(Product, user):
    try:
        vote = Vote.objects.get(juryMember=user, product=Product)

    except Vote.DoesNotExist:
        return ''

    return str(vote.comment)

@register.filter(name='has_group')
def has_group(user, group_name):
    return user.groups.filter(name=group_name).exists()

@register.filter(name='has_Product')
def has_Product(user, Product):
    contact = Contact.objects.get(user=user)
    return Product.objects.filter(contact=contact).filter(pk=Product).exists()
