import base64
from datetime import datetime
from functools import lru_cache

import jdatetime
from django.core.files.base import ContentFile
from django.utils import timezone
from jdatetime import datetime as jalali_datetime


def base64_to_image_file(base64_string, filename="image.jpg"):
    """ convert base64 to image, pdf,..... """

    img_format, img_str = base64_string.split(';base64,')  # split before & after of ';base64,'
    ext = img_format.split('/')[-1]  # split format of file
    return ContentFile(base64.b64decode(img_str), name=f"{filename}.{ext}"), ext


def get_client_ip(request):  # noqa
    forwarded = request.META.get('HTTP_X_FORWARDED_FOR')
    return forwarded.split(',')[0] if forwarded else request.META.get('REMOTE_ADDR')


def shamsi_to_gregorian(shamsi_str: str) -> datetime:
    """
    Convert Shamsi string YYYY/MM/DD to Gregorian datetime
    """
    try:
        year, month, day = map(int, shamsi_str.split('/'))
        jalali_date = jdatetime.date(year, month, day)
        gregorian_date = jalali_date.togregorian()
        return datetime(gregorian_date.year, gregorian_date.month, gregorian_date.day)
    except Exception as e:
        return None


@lru_cache(maxsize=50000)
def shamsi_to_gregorian_cached(shamsi: str):
    try:
        y, m, d = map(int, shamsi.split('/'))
        return jdatetime.date(y, m, d).togregorian()
    except:
        return None


def parse_birthdate(jalali_str):
    if not jalali_str:
        return None

    gregorian_dt = jalali_datetime.strptime(
        jalali_str,
        "%Y/%m/%d"
    ).togregorian()

    return timezone.make_aware(
        gregorian_dt,
        timezone.get_current_timezone()
    )
