import re
from six.moves import urllib

from django import template


register = template.Library()

@register.tag
def sorl_thumbnail(parser, token):
    from sorl.thumbnail.templatetags.thumbnail import thumbnail
    try:
        res = thumbnail(parser, token)
    except Exception as e:
        res = None
        print('1')
    return res


@register.filter
def is_image(path):
    from ..files import is_file_image
    from tEDataProj.settings import MEDIA_ROOT
    path = f'{MEDIA_ROOT}{path}'
    return is_file_image(path)


@register.filter
def thumbnail_format(path):
    match = re.search(r'\.\w+$', path)
    if match:
        ext = match.group(0)
        if ext.lower() in ['.gif', '.png']:
            return 'PNG'
    return 'JPEG'

@register.filter
def filename_from_path(path):
    path = re.sub(r'^.+\/', '', path)
    path = re.sub(r'^.+\\', '', path)
    return path

@register.filter
def unquote(value):
    "urldecode"
    return urllib.parse.unquote(value)
