import base64
import io
import pickle
from copy import deepcopy
from datetime import datetime
from typing import (
    Any,
    Optional,
)
from xml.etree import cElementTree as eTree

from dateutil import tz
from PIL import Image
from model import FiscalType


def get_logo_image_str(
    image_path: str,
) -> str:

    base_width = 100
    with Image.open(fp=image_path) as image:
        width_percent = (base_width / float(image.size[0]))
        height_size = int(float(image.size[1]) * width_percent)
        image = image.resize(size=(base_width, height_size))
        image = image.convert(mode="RGBA")

    return base64.b64encode(_convert_image_to_byte_array(image=image)).decode()


def _convert_image_to_byte_array(
    image: Image,
) -> bytes:

    image_bytes = io.BytesIO()
    image.save(image_bytes, format="PNG")
    image_bytes.seek(0)
    return image_bytes.getvalue()


def is_true(
    value: Optional[str],
) -> bool:

    return (value or "false").lower() == "true"


def get_fiscal_type(
    fiscal_xml: eTree.Element,
) -> str:

    fiscal_xml_str = eTree.tostring(fiscal_xml).decode()
    return FiscalType.NFCE if "<infNFe" in fiscal_xml_str else FiscalType.SAT


def pickle_deep_copy(
    obj: Any,
) -> Any:

    try:
        return pickle.loads(pickle.dumps(obj, -1))
    except pickle.PicklingError:
        return deepcopy(obj)


def convert_from_utf_to_localtime(
    utc: datetime,
) -> datetime:

    from_zone = tz.tzutc()
    to_zone = tz.tzlocal()
    utc = utc.replace(tzinfo=from_zone)
    localtime = utc.astimezone(to_zone)
    return localtime
