#!/usr/bin/python3

import os
import subprocess
import sys

playlistdir = open(os.path.expanduser("~/.plmgmt/playlistdir"), "r").read().strip()

env = dict(os.environ)
date = subprocess.check_output(["date", "+%Y-%m"], universal_newlines=True)[:-1].title()
playlist = os.path.join(playlistdir, "%s.m3u" % (date,))
try:
    pl = open(playlist, "r")
    songs = [s.rstrip() for s in pl.readlines() if s.rstrip()]
except Exception:
    songs = []
files = sys.argv[2:]
new = []
old = []
for f in files:
    g = os.path.relpath(f, os.path.dirname(playlist))
    h = g
    if g not in songs:
        songs.append(g)
        new.append(h)
    else:
        old.append(h)
pl = open(playlist, "w")
pl.writelines(x + "\n" for x in songs)
pl.flush()
pln = os.path.splitext(os.path.basename(playlist))[0]
summary = "Add song to %s" % pln
if new:
    msg = "Added " + ", ".join(new)
else:
    msg = ", ".join(old) + " already in playlist"
subprocess.call(["notify-send", "Add song", msg])
