#!/usr/bin/env python3
#
# Copyright (C) 2019-Present A-Team Digital Solutions
#

from pathlib import Path

BASE = (
    Path(__file__)
    .resolve()
    .parent
    .parent
)
IMAGE_DIR = (
    BASE / "images"
)
CONFIG = (
    BASE / "configs" / "icon.conf"
)
DEFAULT_ICON = (
    "icon-new-blue.png"
)

#
# GET AVAILABLE ICONS
#
def get_available_icons():
    """
    Return every icon image found inside images/.
    """
    icons = []
    for image in sorted(
        IMAGE_DIR.glob("*")
    ):
        if (
            image.is_file()
            and image.suffix.lower() == ".png"
            and "icon" in image.stem.lower()
        ):
            icons.append(
                image.name
            )
    return icons
#
# FILENAME -> FRIENDLY DISPLAY NAME
#
def filename_to_display(
    filename
):
    """
    icon-new-purple.png -> New Purple
    """
    name = Path(
        filename
    ).stem
    name = name.replace(
        "icon",
        ""
    )
    name = name.replace(
        "-",
        " "
    )
    name = name.replace(
        "_",
        " "
    )
    name = name.strip()
    if not name:
        return "Default"
    return name.title()
#
# LOAD SELECTED ICON
#
def load_selected_icon():
    """
    Read configs/icon.conf.
    """
    if not CONFIG.exists():
        return DEFAULT_ICON
    for line in CONFIG.read_text().splitlines():
        line = line.strip()
        if not line.startswith(
            "ICON="
        ):
            continue
        icon = line.split(
            "=",
            1
        )[1].strip()
        if (
            IMAGE_DIR / icon
        ).exists():
            return icon
        break
    return DEFAULT_ICON
#
# SAVE SELECTED ICON
#
def save_selected_icon(
    filename
):
    """
    Save selected launcher icon.
    """
    CONFIG.write_text(
        f"ICON={filename}\n"
    )
#
# GET FULL ICON PATH
#
def get_selected_icon_path():
    """
    Full path to the currently
    selected launcher icon.
    """
    return (
        IMAGE_DIR
        / load_selected_icon()
    )
#
# GET DISPLAY NAMES
#
def get_icon_display_names():
    """
    Return friendly icon names.
    """
    return [
        filename_to_display(
            name
        )
        for name
        in get_available_icons()
    ]
#
# DISPLAY NAME -> FILENAME
#
def display_to_filename(
    display
):
    """
    Converts a friendly display name
    back into the actual filename.
    """
    for filename in (
        get_available_icons()
    ):
        if (
            filename_to_display(
                filename
            )
            == display
        ):
            return filename
    return DEFAULT_ICON
