#!/usr/bin/env python
from __future__ import print_function
import os
import sys
import platform
import subprocess
import argparse
import ConfigParser
from musicquery import MusicQuery

def list2str(lst):
    return ' '.join(lst)

def play_music(song_path, title=None, artist=None):
    DEVNULL = open(os.devnull,'w')
    if platform.system() == 'Darwin':
        cmd = 'open'
    else:
        cmd = 'xdg-open'
    subprocess.call([cmd, song_path], stdout=DEVNULL, stderr=subprocess.STDOUT)
    print ('Playing '+ title + ' By ' + artist)

def set_config(music_dir, CONF_FILE):
    config = ConfigParser.ConfigParser()
    if not os.path.exists(os.path.expanduser(music_dir)):
        print("Invalid music_dir path")
        sys.exit(1)
    conf_file = open(CONF_FILE,"a+")
    config.readfp(conf_file)
    config.set('xplay conf', 'music_dir', music_dir)
    config.write(conf_file)
    conf_file.close()

def get_music_dir(CONF_FILE):
    config = ConfigParser.ConfigParser()
    conf_file = open(CONF_FILE)
    config.readfp(conf_file)
    return config.get('xplay conf', 'music_dir')

def main(args):
    artist, title, genre = None, None, None
    CONF_FILE = os.path.expanduser('~/.xplay.conf')
    if not os.path.exists(CONF_FILE):
        conf = open(CONF_FILE, "w")
        conf.write("[xplay conf]\nmusic_dir= ~/Music/")
        conf.close()
    MUSIC_DIR = os.path.expanduser(get_music_dir(CONF_FILE))
    if args.set:
        set_config(args.set, CONF_FILE)
        return None
    if args.artist:
        artist = list2str(args.artist)
    if args.genre:
        genre = list2str(args.genre)
    if args.title:
        title = list2str(args.title)
    #print "title:%s,genre:%s,artist:%s"%(title,genre,artist)
    song_obj = MusicQuery(music_dir=MUSIC_DIR, artist=artist, genre=genre, title=title)
    if song_obj.status == 'ok':
        play_music(song_obj.song_path, title=song_obj.title, artist=song_obj.artist)
    else:
        print(song_obj.error, "!!")
        sys.exit(1)
if __name__=='__main__':
    parser = argparse.ArgumentParser(description='Play any song from terminal')
    parser.add_argument('-s', '--set', type=str, action='store', help='set music_dir folder, default is ~/Music/')
    parser.add_argument('-g', '--genre', nargs='+', help='play song of the given genre')
    parser.add_argument('-a', '--artist', nargs='+', help='play song of the given artist')
    parser.add_argument('-t', '--title', nargs='+', help='play song of the given title')
    args = parser.parse_args()
    main(args)


