#!python
# Made By Nima Fanniasl, smartnima.com - July 16 2022 :)
import os
import argparse
import requests

# message handling
# levels ( Error, Warning, Info, Text )
# note: levels and text with string types


def message(level, text):
    print(f"{level}:\n{text}")


try:
    import araste
except:
    message("Error", "Araste is not installed")
    exit(1)


def main():
    parser = argparse.ArgumentParser(description="Get Fonts For Araste")
    parser.add_argument("command", type=str, help="install, remove, update, list")
    parser.add_argument("Font_name", type=str, help="Font Name, Like: aipara", nargs="*")
    parser.add_argument("-r", "--repository", type=str,
                        help="repo to get fonts from. (github_username/repository)", default="ekm507/araste-fonts")
    args = parser.parse_args()
    fonts_names = args.Font_name
    command = args.command
    font_dir = get_font_dir()
    if command == "install" or command == "Install":
        download_font(fonts_names, font_dir, repository=args.repository)
    elif command == "remove" or command == "Remove":
        remove_font(fonts_names, font_dir)
    elif command == "update" or command == "Update":
        download_font(fonts_names, font_dir, repository=args.repository, update=True)
    elif command == "list" or command == "List":
        list_fonts(repository=args.repository)
    else:
        print(f"Invalid command: {command}")
        exit(1)



def get_font_dir():
    return araste.__file__.replace("__init__.py", "") + "fonts"


def remove_font(fonts_names, font_dir):
    error = False
    for font in fonts_names:
        if f"{font}.aff" in os.listdir(font_dir):
            os.remove(f"{font_dir}/{font}.aff")
            print(f"{font} font removed.")
        else:
            print(f"{font} font not found.")
            error = True
    if error:
        exit(1)
    exit(0)


def download_font(fonts_names, font_dir, repository="ekm507/araste-fonts", update=False):
    error = False
    for font in fonts_names:
        
        if '/' in font:
            font_filename = os.path.realpath(str(font))
            font_name = os.path.basename(font)
            if font_name in os.listdir(font_dir) and not update:
                print(f"{font} already exists.")
                continue

            elif font_name not in os.listdir(font_dir) and update:
                print(f"{font} is not installed")
                error = True
                continue

            os.popen(f'cp {font_filename} {font_dir}')
            print(f"{font} Font Installed :)")
        
        else:

            if f"{font}.aff" in os.listdir(font_dir) and not update:
                print(f"{font} already exists.")
                continue
            elif f"{font}.aff" not in os.listdir(font_dir) and update:
                print(f"{font} is not installed")
                error = True
                continue
            else:
                print(f"Downloading Font: {font}")
                url = f"https://raw.githubusercontent.com/{repository}/main/Fonts/aff3/{font}.aff"
                r = requests.get(url)
                if r.status_code != 404:
                    with open(f"{font_dir}/{font}.aff", "wb") as f:
                        f.write(r.content)
                    print(f"{font} Font Downloaded :)")
                    continue
                else:
                    print(f"{font} Font Not Found :(")
                    error = True
                    continue
    if error:
        exit(1)
    exit(0)



def list_fonts(repository="ekm507/araste-fonts"):
    font_page_url = f'https://raw.githubusercontent.com/{repository}/main/Fonts/aff3/list.md'
    font_page = requests.get(font_page_url)
    print(font_page.text)

if __name__ == "__main__":
    main()
