#!/usr/bin/env python3

import gi
gi.require_version('Playerctl', '2.0')

from gi.repository import Playerctl, GLib
import argparse, sys

parser = argparse.ArgumentParser()
parser.add_argument('-a', '--active-color', type=str, metavar='active color', dest='active')
parser.add_argument('-i', '--inactive-color', type=str, metavar='inactive color', dest='inactive')
args = parser.parse_args()

if args.active is None:
	sys.exit('Active color not provided.')
if args.inactive is None:
	sys.exit('Inactive color not provided.')

def get_icon(status):
	icons = {
		"Playing": "",
		"Paused": ""
	}
	return icons.get(status, "")

def on_metadata(player, metadata, manager):
	keys = metadata.keys()
	if 'xesam:artist' in keys and 'xesam:title' in keys:
		print('%{{F{color}}} {status} {artist} - {title}%{{F-}}'.format(
			color=args.active,
			status=get_icon(player.get_property('status')),
			artist=metadata['xesam:artist'][0],
			title=metadata['xesam:title']
		))

def init_player(name):
	if name.name in ['spotify']:
		player = Playerctl.Player.new_from_name(name)
		player.connect('metadata', on_metadata, manager)
		manager.manage_player(player)

def on_name_appeared(manager, name):
	init_player(name)

def on_player_appeared(manager, player):
	print('%{{F{color}}} {status} {artist} - {title}%{{F-}}'.format(
			color=args.active,
			status=get_icon(player.get_property('status')),
			artist=player.get_artist(),
			title=player.get_title()
		))

def on_player_vanished(manager, player):
	print('%{{F{color}}} Nothing is playing%{{F-}}'.format(color=args.inactive))

manager = Playerctl.PlayerManager()

manager.connect('name-appeared', on_name_appeared)
manager.connect('player-appeared', on_player_appeared)
manager.connect('player-vanished', on_player_vanished)

names_list = manager.props.player_names
if not names_list:
	print('%{{F{color}}} Nothing is playing%{{F-}}'.format(color=args.inactive))
else:
	for name in names_list:
		init_player(name)

main = GLib.MainLoop()
main.run()
