from common import *
from spotifyFetch import fetch_data
import cmd

playlists = get_data('playlistTracks')
top_artists = get_data('top_artists')
top_tracks = get_data('top_tracks')
user_tracks = get_data('tracks')


def get_playlist_names():
    return [name for name, items in playlists.items()]


def get_artists_str(artists_pack):
    track_artists = [artist['name'] for artist in artists_pack]
    artists = " ".join(track_artists)
    return artists


def print_playlist_tracks(name):
    print(name)
    for track in playlists[name]:
        track_data = track['track']
        track_name = track_data['name']
        artists = get_artists_str(track_data['artists'])
        print(f"   '{track_name}' - '{artists}' ")


def print_top_artists():
    for artist in top_artists:
        name = artist['name']
        print(f"   '{name}'")


def print_top_tracks():
    for track in top_tracks:
        track_name = track['name']
        artists = get_artists_str(track['artists'])
        print(f"   '{track_name}' - '{artists}' ")


def print_stats():
    print(f" tracks - {len(user_tracks)}")
    print(f" playlists - {len(playlists)}")

    for name, tracks in playlists.items():
        print(f"    '{name}' - {len(tracks)}")

    print(f" top tracks - {len(top_tracks)}")
    print(f" top artists - {len(top_artists)}")


def print_tracks():
    for trackItem in user_tracks:
        track = trackItem['track']
        print(f"    '{track['name']}' - {get_artists_str(track['artists'])}")


class Interpreter(cmd.Cmd):
    intro = "Welcome to the interactive command loop. Type help or ? to list commands.\n"
    prompt = "(spotify) "

    def do_playlists(self, arg):
        """prints user playlists"""
        print("\n".join(get_playlist_names()))

    def do_playlist_tracks(self, arg):
        """prints playlist [name]"""
        try:
            name = arg.split()[0]
            print_playlist_tracks(name)
        except IndexError:
            print("Invalid input")

    def do_top_artists(self, arg):
        """Top artists"""
        print_top_artists()

    def do_top_tracks(self, arg):
        """Top tracks"""
        print_top_tracks()

    def do_stat(self, arg):
        """Print stats"""
        print_stats()

    def do_tracks(self, arg):
        """Print tracks"""
        print_tracks()

    def do_fetch(self, arg):
        """Fetch all spotify data"""
        try:
            fetch_data()
        except ValueError:
            print("Can not fetch the data.")

    def do_exit(self, arg):
        """Exit the command loop: exit"""
        print("Goodbye!")
        return True


if __name__ == '__main__':
    Interpreter().cmdloop()
