!/usr/bin/env python

# Rename? gm fs to playlists

# gm-utp.py
# google music api - upload to playlist
# aguments 
# 	folder containing .mp3's
#	name of playlist to create
# 
# intall : pip install googleapi
# tested with python version 2.7.2


# TODO
# - fix check-for-existing-playlist to only add songs if they are new
# - fix check for existing song in playlist
# - fix trailing / in folder split
# - add dirwalk, if it is a leaf folder add it as a playlist
# - move add songs to playlist to outside of loop
# - add to multiple playlists (-n xxx yyy zzz), works nicely with -d maybe
# - Try/Catch uploading#


from gmusicapi.api import Api
from getpass import getpass
import os
import argparse

def parse(): 
	parser = argparse.ArgumentParser(
		description='Upload music to Google Music Playlists')
	parser.add_argument(
		'folder', action='store',
		help='the folder of music to upload')
	parser.add_argument(
		'-n', action='store', dest='playlist_name', 
		help='set the playlist name')
	parser.add_argument(
		'-d', action='store_true', default=False, 
		help='set playlist_name=folder')
	parser.add_argument(
		'-u', action='store', dest='user_name', 
		help='Google Username')
	parser.add_argument(
		'-p', action='store', dest='password', 
		help='Google Single Application Password reccomended')
	parser.add_argument(
		'-v', action='store_true', default=False,
		help='verbose mode')
	
	args = parser.parse_args()

	# I have a feeling this logic can be done by argparse
	# For now this is good enough
	if args.playlist_name == None and args.d == True :
		tmp = args.folder.split('/')
		args.playlist_name = tmp[len(tmp)-1] # least sig dir
	elif args.playlist_name != None and args.d == True :
		if args.v : print "Warning : -n has priority, ignoring -d"

	return args

def init(args):
	api = Api()
	if args.user_name == None:
		email =	 raw_input("Email: ")
	else :
		email = args.user_name
	if args.password == None:
		password = getpass()
	else :
		password = args.password 
	print "Signing in : " + email
	logged_in = api.login(email, password)
    	return api

def main():
	# Parse the cli args then setup a google music api connection
	args = parse()
	api = init(args)

	# check if authentication succeded
	if not api.is_authenticated():
		print "Sorry, those credentials weren't accepted."
		return
	if args.v : print "Login Success"

	user_playlists = api.get_all_playlist_ids(auto=False,user=True)["user"]
	if not args.playlist_name in user_playlists :
		if args.v : print "Creating Playlist : " + args.playlist_name
		playlist_id = api.create_playlist(args.playlist_name)
	else : 
		playlist_id = user_playlists[args.playlist_name]	
		print "Current Playlist: "
		print api.get_playlist_songs(playlist_id)

	# get to the right dir where the files are
	os.chdir(args.folder)
	
	# upload and playlist-ize each .mp3 in the folder
	for files in os.listdir("."):
		if files.endswith(".mp3"):
			if args.v : print "Uploading  : " + files
			u = api.upload(files)
			song_id = u[files]
			api.add_songs_to_playlist(playlist_id, song_id)
			
	#It's good practice to logout when finished.
	if args.v : print "Logging off."
	api.logout()

if __name__ == '__main__':
    main()
