#!/usr/bin/env python3

import os
import yaml
import subprocess
from pathlib import Path

"""
All of the dirs are stored in different variables located in my ~/.config/zsh/.zshrc
ROOT
NOTES_DIR
CURRENT_COURSE
"""

def rofi(prompt, options, rofi_args=[], fuzzy=True):
    optionstr = '\n'.join(option.replace('\n', ' ') for option in options)
    args = ['rofi', '-sort', '-no-levenshtein-sort']
    if fuzzy:
        args += ['-matching', 'fuzzy']
    args += ['-dmenu', '-p', prompt, '-format', 's', '-i']
    args += rofi_args
    args = [str(arg) for arg in args]

    result = subprocess.run(args, input=optionstr, stdout=subprocess.PIPE, universal_newlines=True)
    returncode = result.returncode
    stdout = result.stdout.strip()

    selected = stdout.strip()
    try:
        index = [opt.strip() for opt in options].index(selected)
    except ValueError:
        index = -1

    if returncode == 0:
        key = 0
    if returncode == 1:
        key = -1
    if returncode > 9:
        key = returncode - 9

    return key, index, selected

EDITOR = 'nvim'
TERMINAL = 'xfce4-terminal'
NOTES_DIR = Path('~/Documents/notes').expanduser()
ROOT = '{}/Grade-10/semester-1'.format(NOTES_DIR)
CURRENT_COURSE = '{}/current-course'.format(NOTES_DIR)

classes = [os.path.join(ROOT, o) for o in os.listdir(ROOT)
          if os.path.isdir(os.path.join(ROOT, o))]
titles = []

for classs in classes:
    info = open('{}/info.yaml'.format(classs))
    file_info = yaml.load(info, Loader=yaml.FullLoader)

    titles.append(file_info['title'] + ' (' + file_info['short'] + ')')

key, index, selected = rofi('Select class', titles, [
    '-lines', 5,
    '-markup-rows',
    '-kb-row-down', 'Down',
    '-kb-custom-1', 'Ctrl+n'
])

if os.path.isdir(CURRENT_COURSE):
    os.remove(CURRENT_COURSE)
os.symlink(classes[index], CURRENT_COURSE)

