from Moodipy.SpotifyAuthorization import Authorization
from Moodipy.UserSummary import Person
import random


def generatePlaylist():

    """
    Step 0: Get Users Liked Songs
    """
    user, client = Authorization()
    print("checkpoint 0")

    user_songs = user.get_user_saved_tracks()

    print("checkpoint 1")

    """
    Step 1: Get Tracks Matching User Emotion
    """
    if len(Person.currentmood) == 1:
        first_emotion = Person.currentmood[0]
        second_emotion = None
    else:
        first_emotion = Person.currentmood[0]
        second_emotion = Person.currentmood[1]

    emotion_tracks = user.get_user_emotion_tracks(client=client, user_tracks=user_songs, base_emotion=first_emotion,
                                                  second_emotion=second_emotion)

    print("checkpoint 2")

    """
    Step 2: Create a Playlist for the User
    """
    emotion_tracks = random.sample(emotion_tracks, 25)

    tracks = {}
    for track in emotion_tracks:
        tracks[track['name']] = track['artists'][0]['name']


    Person.playlistName = Person.setPlaylistName(Person, Person.moodLabel, Person.currentmood)
    playlist_name = Person.playlistName

    description = "Enjoy your \"" + Person.moodLabel + "\" Playlist generated by Moodipy, an app that uses sentiment " \
                                                     "analysis to create a playlist that matches someone's mood. "

    user.create_playlist(playlist_name=playlist_name, description=description)
    print("checkpoint 3")

    """
    Step 3: Add Songs to a Playlist
    """
    user.add_to_playlist(playlist_name=playlist_name, playlist_tracks=emotion_tracks)
    print("checkpoint 4")

    return tracks
