# AUTOGENERATED! DO NOT EDIT! File to edit: ../../nbs/utils/convert.ipynb.

# %% auto 0
__all__ = ['rename_filepath_to_match_datatype', 'change_suffix', 'ImageBlockConverter', 'md', 'convert_html_to_markdown',
           'convert_remove_html_tags', 'convert_enum_member_to_name', 'convert_str_to_snake_case',
           'convert_str_remove_accents', 'convert_str_keep_alphanumeric', 'convert_str_file_name',
           'convert_str_to_date', 'convert_datetime_to_str', 'sort_dictionary']

# %% ../../nbs/utils/convert.ipynb 3
from enum import Enum

import os
import re
import pathlib
import unicodedata


from markdownify import MarkdownConverter
import PIL
from bs4 import BeautifulSoup


import datetime as dt
from dateutil.parser import parse as dtu_parse

# %% ../../nbs/utils/convert.ipynb 6
def rename_filepath_to_match_datatype(data, file_path):
    is_path_ext = os.path.splitext(file_path)[-1].lower()

    old_suffix = pathlib.Path(file_path).suffix if is_path_ext else None

    new_suffix = ""

    if isinstance(data, str) or isinstance(data, bytes) or isinstance(data, bytearray):
        new_suffix = ".txt"
    if isinstance(data, dict):
        new_suffix = ".json"

    file_path = file_path + new_suffix

    if old_suffix:
        file_path = file_path.replace(old_suffix, "")

    return file_path

# %% ../../nbs/utils/convert.ipynb 8
def change_suffix(filename, new_extension):
    is_exist = os.path.exists(filename)

    p = pathlib.PurePath(filename)
    p = p.with_suffix(new_extension)

    if is_exist:
        p = pathlib.Path(filename)
        p = p.rename(p.with_suffix(new_extension))

    return str(p)

# %% ../../nbs/utils/convert.ipynb 11
class ImageBlockConverter(MarkdownConverter):
    """
    Create a custom MarkdownConverter that adds two newlines after an image
    """

    def convert_img(self, el, text, convert_as_inline, is_resize: bool = True):
        """
        custom image downloader for ImabeBlockConverter
        will handle resize
        """

        if is_resize:
            style_obj = {
                (obj.split(":")[0].strip()): obj.split(":")[1].strip()
                for obj in el.get("style").split(";")
                if ":" in obj
            }

            file_path = os.path.join(
                os.path.dirname(self.options["file_path"]), el["src"]
            )

            image = PIL.Image.open(file_path)

            width = style_obj["width"].replace("px", "")
            width = int(float(width))

            height = style_obj["height"].replace("px", "")
            height = int(float(height))

            new_image = image.resize((width, height))
            new_image.save(file_path)

        return super().convert_img(el, text, convert_as_inline)


def md(html, **options):
    """Create shorthand method for handling conversion"""
    return ImageBlockConverter(**options).convert(html)

# %% ../../nbs/utils/convert.ipynb 12
def convert_html_to_markdown(file_path):
    """converts html file to markdown in place"""

    with open(file_path, encoding="utf-8") as f:
        html = f.read()

    markdown_content = md(
        str(html),
        keep_inline_images_in=["td", "span"],
        file_path=file_path,
        is_resize=True,
    )

    md_path = file_path.replace(".html", ".md")

    with open(md_path, "w+", encoding="utf-8") as f:
        f.write(markdown_content)

    return

# %% ../../nbs/utils/convert.ipynb 13
def convert_remove_html_tags(html_string: str) -> str:
    """
    Clean an HTML string using BeautifulSoup.

    Args:
        html_string (str): The HTML string.

    Returns:
        str: The cleaned string.
    """
    soup = BeautifulSoup(html_string, "html.parser")
    clean_string = soup.get_text()
    return clean_string

# %% ../../nbs/utils/convert.ipynb 15
def convert_enum_member_to_name(enum_member):
    return enum_member.name if isinstance(enum_member, Enum) else enum_member

# %% ../../nbs/utils/convert.ipynb 16
def convert_str_to_snake_case(text_str):
    """converts 'snake_case_str' to 'snakeCaseStr'"""

    return text_str.replace(" ", "_").lower()

# %% ../../nbs/utils/convert.ipynb 17
def convert_str_remove_accents(text_str: str) -> str:
    return "".join(
        c
        for c in unicodedata.normalize("NFD", text_str)
        if unicodedata.category(c) != "Mn"
    )

# %% ../../nbs/utils/convert.ipynb 19
def convert_str_keep_alphanumeric(text_str) -> str:
    pattern = "[^0-9a-zA-Z_\-\s]+"

    return re.sub(pattern, "", text_str)

# %% ../../nbs/utils/convert.ipynb 20
def convert_str_file_name(text_str: str) -> str:
    """convert strings to clean file name or url"""

    return convert_str_keep_alphanumeric(
        convert_str_to_snake_case(convert_str_remove_accents(text_str))
    )

# %% ../../nbs/utils/convert.ipynb 22
def convert_str_to_date(datefield: str) -> dt.datetime:
    """converts string date to datetime object"""
    return dtu_parse(datefield) if datefield else None

# %% ../../nbs/utils/convert.ipynb 24
def convert_datetime_to_str(date_date: dt.datetime, format_str="%Y-%m-%d %H:%M") -> str:
    return date_date.strftime(format_str) if date_date else None

# %% ../../nbs/utils/convert.ipynb 25
def sort_dictionary(my_dict):
    my_keys = list(my_dict.keys())
    my_keys.sort()
    return {key: my_dict[key] for key in my_keys}
