#!/usr/bin/env python3
import os, sys
from irank.config import IrankOptionParser

def main(base, name, *directories):
	assert base is not None, "please supply a base directory!"
	if not directories: directories = (name,)
	fullpath = os.path.join(base, name + ".m3u")
	dirpaths = [os.path.join(base, d) for d in directories]
	with open(fullpath, 'w') as f:
		for dirpath in dirpaths:
			filepath = lambda p: os.path.join(dirpath, p)
			ctime = lambda p: os.stat(filepath(p)).st_ctime
			isfile = lambda p: os.path.isfile(filepath(p))
			files = filter(isfile, os.listdir(dirpath))
			for filename in sorted(files, key=ctime):
				print(filename, file=f)

def run():
	usage = """Usage: %prog [OPTIONS] playlist-name [directoryname [directoryname ...]]

playlist will be created in the `base` directory (specified via options, falling back to the configured android path)"""
	p = IrankOptionParser()
	p.add_option("--base", help="base directory to create playlist in", default=None)
	opts, args = p.parse_args()
	try:
		main(opts.base or opts.android, *args)
	except TypeError:
		p.print_help()
		return 1

if __name__ == '__main__':
	sys.exit(run())
