#!/usr/bin/env python

from pathlib import Path
import subprocess

HOME = Path.home()

SEARCH_DIRS = [
    HOME.joinpath("Projects"),
    HOME.joinpath("Repositories"),
    HOME.joinpath("SR"),
]


def get_search_project_dirs():
    for path in SEARCH_DIRS:
        if not path.exists():
            continue
        for subdir in path.iterdir():
            if subdir.is_dir():
                yield subdir


def main():
    project_paths = sorted(get_search_project_dirs(), key=lambda p: p.name.lower())
    try:
        project_paths.remove(Path.home())  # Don't try and edit home dir
    except ValueError:
        pass
    home_dir = str(HOME) + "/"
    project_paths_display = [str(project).replace(home_dir, "") for project in project_paths]

    selected_project = subprocess.run(["rofi", "-dmenu", "-no-case-sensitive", "-format", "i", "-p", "Project"], input="\n".join(project_paths_display).encode(), stdout=subprocess.PIPE)
    selected_project.check_returncode()

    selected_index = int(selected_project.stdout.strip())
    if selected_index == -1:
        return  # This is hit when enter is hit on no results
    subprocess.run(['code', project_paths[selected_index]])


if __name__ == '__main__':
    main()
