#!/usr/bin/python2
#-*- coding: utf-8 -*-

import os.path, shutil, sys
import mutagen
import subprocess

print("Default encoding: " + sys.stdout.encoding)

FILE = '/home/my-home/my-playlist.m3u'
DIR = '/some-target-directory'

# Make sure we have two arguments and an option
if len(sys.argv) == 3:
    dryrun = False
    flacenc = False
    playlist = sys.argv[1]
    targetdir = sys.argv[2]
elif len(sys.argv) in (4,5):
    opts = [o for o in sys.argv[1:len(sys.argv)-1] if o.startswith('--')]
    print("Options: %s" % opts)
    dryrun = '--dry' in opts
    flacenc = '--flacenc' in opts
    playlist = sys.argv[2]
    targetdir = sys.argv[3]
else:
    print("Usage: %s [--dry] <playlist file> <target dir>" % sys.argv[0])
    sys.exit(1)

if dryrun:
    def copyfile(a,b):
        print("\tDry run:\n\tFrom: %s\n\tTo: %s" % (s, targetpath))
else:
    def copyfile(a,b):
        try:
            if flacenc and a.lower().endswith('.flac'):
                infile = os.path.abspath(a)
                b = b.lower().rstrip('.flac') + '.ogg'
                outfile = os.path.abspath(b)
                try:
                    print(u"\tConverting:\n\tFrom: %s\n\tTo: %s" % (infile, outfile))
                except Exception, e:
                    print "Error: ", e
                call = u'ffmpeg -i "%s" "%s"' % (infile, outfile)
                output, error = subprocess.Popen(call, stdout=subprocess.PIPE,
                        stderr=subprocess.PIPE, shell=True).communicate()
                if error:
                    print("\tError: %s" % error)
                print output
            else:
                print("\tCopying:\n\tFrom: %s\n\tTo: %s" % (a, b))
                shutil.copy(a.encode('utf-8'), b.encode('utf-8'))
        except Exception, e:
            print "Error: " + str(e)

for i, s in enumerate(open(playlist)):
    s = s.rstrip()
    try:
        audio = mutagen.File(s)
        artist = audio.get('artist') or audio.get('TPE1')
        title = audio.get('title') or audio.get('TIT2')

        if type(artist) == list and len(artist) > 0:
            artist = artist[0]

        if type(title) == list and len(title) > 0:
            title = title[0]

        print("File: %s" % s)
        print("\tArtist: %s" % artist)
        print("\tTitle: %s" % title)

        if artist and title:
            songlabel = "%s - %s%s" % (artist, title, os.path.splitext(s)[1])
        else:
            songlabel = os.path.basename(s)

        targetpath = os.path.join(targetdir, '%02d - %s' % (i+1, songlabel))
        copyfile(s, targetpath)
    except IOError, e:
        sys.stderr.write('warning: %s\n' % e)
