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


def generatePlaylist():
    
    try:

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

        user_songs = user.get_user_saved_tracks()
        if len(user_songs) > 300: # Check Random 300 in User Library
            user_songs = sample(user_songs, 300)

        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
        """
        if len(emotion_tracks) > 30: # Show random 30 (average for Spotify playlist creators)
            emotion_tracks = sample(emotion_tracks, 30)

        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
    
    except(spotipy.exceptions.SpotifyException, requests.exceptions.HTTPError,spotipy.oauth2.SpotifyOauthError):
        return None

