from django import template
from datetime import datetime

from panel.helper_excel import shamsi_date, to_locale_str

register = template.Library()


@register.filter(name='jalali')
def jalali(value):
    if not value:
        return ""

    try:
        if isinstance(value, str):
            string = str(value).strip()

            date_formats = [
                '%Y-%m-%dT%H:%M:%S.%fZ',
                '%Y-%m-%dT%H:%M:%SZ',
                '%Y-%m-%dT%H:%M:%S.%f',
                '%Y-%m-%dT%H:%M:%S',
                '%Y-%m-%d %H:%M:%S.%f',
                '%Y-%m-%d %H:%M:%S',
                '%Y-%m-%d'
            ]
            try:
                for fmt in date_formats:
                    try:

                         value=datetime.strptime(string, fmt).date()
                         return shamsi_date(value,in_value=True)
                    except ValueError:
                        continue
            except:
                return '-'

        if hasattr(value, 'date'):
            value = value.date()

        return shamsi_date(value,in_value=True)
    except:
        return '-'


@register.filter(name='isNone')
def is_none(value):
    if value is None:
        return "-"
    return value


@register.filter(name='toLocaleStr')
def to_locale_string(value):
    if value is None:
        return "-"
    return to_locale_str(value)


@register.filter(name='int')
def to_int(value):
    if value is None:
        return "-"
    return int(value)
