#!/usr/bin/python
# -*- coding: utf-8 -*-
# 2019/12/19
import sys, os

TRACK_DIR = "music"

def run_cmd(command, display = False):
    if display:
        print(command)

    return os.popen(command).read().strip()

def cd_wrapper():
    if len(sys.argv) <= 1:
        return False

    pid_list = run_cmd("pgrep vlc")

    if "--stop" in sys.argv:
        for pid in pid_list.splitlines():
            os.popen("kill {0}".format(pid))

        return True

    if pid_list != "":
        return False

    search_path = os.path.join(appdir, TRACK_DIR)
    track_num = sys.argv[1]

    if len(track_num) <= 1:
        track_num = "0" + track_num 

    for fn in os.listdir(search_path):
        if track_num in os.path.splitext(os.path.basename(fn))[0]:
            track_path = os.path.join(TRACK_DIR, fn)
            cmd = "cvlc --aout=alsa --alsa-gain 0.5 --play-and-exit --repeat \"{0}\" &".format(track_path)
            os.popen(cmd)
            break

if __name__ == "__main__":
    appdir = os.path.abspath(os.path.dirname(sys.argv[0]))
    os.chdir(appdir)
    cd_wrapper()
