import os
from typing import Any
import imageio
import re


def atoi(text: str) -> Any:
    return int(text) if text.isdigit() else text


def natural_keys(text: str) -> list:
    """
    alist.sort(key=natural_keys) sorts in human order
    http://nedbatchelder.com/blog/200712/human_sorting.html
    (See Toothy's implementation in the comments)
    """
    return [atoi(c) for c in re.split(r"(\d+)", text)]


def get_sorted_images(png_dir: str) -> list:
    output = os.listdir(png_dir)
    output.sort(key=natural_keys)
    return output


def convertir_images(png_dir: str):
    images = []
    for file_name in get_sorted_images(png_dir):
        if file_name.endswith(".png"):
            file_path = os.path.join(png_dir, file_name)
            print(file_path)
            images.append(imageio.v2.imread(file_path))
    if len(images) >= 1:
        imageio.mimsave(os.path.join(png_dir, "animated_gif.gif"), images)


if __name__ == "__main__":
    import argparse

    parser = argparse.ArgumentParser(
        usage=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
    )
    parser.add_argument(
        "--path",
        type=str,
        default="",
        help="path to png iamges",
    )
    args = parser.parse_args()

    if args.path != "":
        convertir_images(args.path)
