from flask import redirect
from spotify_adapter.adapter import Adapter as Spotify
from player.ssh_linux import SshLinuxPlayer
from db.play_logger import PlayLogger

def play_media(config, media_type, media_id):
    player = SshLinuxPlayer(config.player_ssh_ip)

    # Send change cmd ASAP, so that user won't have to wait for Spotify queries before hearing the change
    # player.cmd_playmedia(media_type, media_id)

    sp = Spotify(config.client_id, config.client_secret, config.redirect_uri, config.username)

    curr_track = player.cmd_get_metadata()['mpris:trackid']
    curr_track, curr_album, curr_artist = sp.get_track_ids(curr_track)

    new_id = 'spotify:{}:{}'.format(media_type, media_id)
    if media_type == 'artist':
        new_track, new_album, new_artist = None, None, new_id
    elif media_type == 'album':
        new_track, new_album, new_artist = None, new_id, sp.get_artist_from_album(new_id)
    elif media_type == 'track':
        new_track, new_album, new_artist = sp.get_track_ids(new_id)
    else:
        # WTF?
        new_artist, new_album, new_track = None, None, None

    print "Playing {} - {} from {}".format(curr_track, curr_album, curr_artist)
    print "Change to {} - {} from {}".format(new_track, new_album, new_artist)

    PlayLogger(config.db_name).log_play(new_artist,  new_album,  new_track,
                                        curr_artist, curr_album, curr_track)

    return redirect('/list_artists')
    
