#!/usr/bin/env python3
import os
import urllib.request
import gi
gi.require_version('Playerctl', '2.0')
from gi.repository import Playerctl, GLib

metadata_file = '/tmp/kuba_now_playing'
album_cover_file = '/tmp/kuba_now_playing_cover.png'
manager = Playerctl.PlayerManager()

last_spotify_metadata = None # Keep this as spotify gives several notifications

def on_play(player, status, manager):
#    print('player is playing: {}'.format(player.props.player_name))
    pass

def download_album_cover(url):
    image = urllib.request.urlopen(url)
    with open(album_cover_file,'wb') as output:
        output.write(image.read())

space = '                       '
def on_metadata(player, metadata, manager):
    global last_spotify_metadata
    if last_spotify_metadata == metadata:
        return

    last_spotify_metadata = metadata
    keys = metadata.keys()
    with open(metadata_file, 'w+') as f:
        f.write('{}{}\n'.format(space, metadata['xesam:artist'][0]))
        f.write('{}{}\n'.format(space, metadata['xesam:title']))
        f.write('{}{}'.format(space, metadata['xesam:album']))
        download_album_cover(metadata['mpris:artUrl'])

def init_player(name):
    # choose if you want to manage the player based on the name
    if name.name in ['spotify']:#, 'vlc', 'cmus']:
        player = Playerctl.Player.new_from_name(name)
        #player.connect('playback-status::playing', on_play, manager)
        player.connect('metadata', on_metadata, manager)
        manager.manage_player(player)
        return player

def on_name_appeared(manager, name):
    player = init_player(name)
#    if player != None:
#        print('player has appeared: {}'.format(player.props.player_name))

def on_player_vanished(manager, player):
    print('player has exited: {}'.format(player.props.player_name))
    os.remove(metadata_file)

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

for name in manager.props.player_names:
    init_player(name)

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

