#!/usr/bin/python -u
from subprocess import run, CalledProcessError
from glob import glob
import shutil
import sys
import os


def fzf(input_list) -> str:
    try:
        output = run(
            ['fzf'], input='\n'.join(
                input_list), capture_output=True, check=True, encoding='utf-8')
    except CalledProcessError:
        sys.exit(1)
    return output.stdout.strip()


def find_desktop(path) -> dict:
    return {
        file.split('/')[-1]: file
        for file in glob(path)
    }


def main() -> None:
    # Get all desktop files
    system = find_desktop('/usr/share/applications/*.desktop')
    user = find_desktop(
        os.path.expanduser('~/.local/share/applications/*.desktop'))

    # Update dictionary with user files
    system.update(user)

    # Get selection
    selection = fzf(list(system))

    # If file isn't in user directory, copy it to override it
    if '/.local/share/applications/' not in system[selection]:
        print('Copying file to ~/.local/share/applications/')
        path = os.path.expanduser(f'~/.local/share/applications/{selection}')
        shutil.copyfile(system[selection], path)
    else:
        path = system[selection]

    # Edit the file
    print(f'Editing {path}')
    run(['nvim', path])


if __name__ == "__main__":
    main()
