import json
import requests
from secrets import spotify_user_id
from refresh import Refresh

class SaveSongs:
    def __init__(self):

        self.user_id = spotify_user_id
        self.spotify_token = ""
        self.tracks = ""

        print("Spotify Add 50 Last Played Tracks to PLAYED LOG - The Vikings [v30-SEP-2020 @ 14:57]")

        # URI of PLAYED LOG playlist.
        self.new_playlist_id = "0pLPfZawitUUdNxbMOayyn" 

    def find_songs(self):

        # Get the 50 Last Played Tracks.
        print("• Getting the 50 Last Played Tracks list.")

        # The API call is...[This info not available via URI on Spotify].
        query = "https://api.spotify.com/v1/me/player/recently-played"

        # The query (limit set to 50 'The maximum' and the Authorisation Token).
        response = requests.get(query,"limit=50", headers={"Content-type": "application/json","Authorization": "Bearer {}".format(self.spotify_token)})

        # The response to the query.
        response_json = response.json()
        print("Response should be 200 = " + str(response))

        # Loop through the Recently Played list and get the track info.
        for i in response_json["items"]:
            self.tracks += (i["track"]["uri"] + ",")
        self.tracks = self.tracks[:-1]

        self.add_to_playlist()


    # Add [append- NO] the tracks to the PLAYED LOG Playlist.
    def add_to_playlist(self):
        print("• Adding tracks.")
     
        # The API call to add the tracks.
        query = "https://api.spotify.com/v1/playlists/{}/tracks?uris={}".format(self.new_playlist_id,self.tracks)
        # query = "https://api.spotify.com/v1/playlists/{}/tracks?uris={}".format(self.new_playlist_id,self.nowtrack)

        # The 'PUT' [ADDS] query is submitted with Spotify Token.
        response = requests.put(query, headers={"Content-type": "application/json","Authorization": "Bearer {}".format(self.spotify_token)})
        
        # The 'POST' [APPENDS] query is submitted with Spotify Token.
        # response = requests.post(query, headers={"Content-type": "application/json","Authorization": "Bearer {}".format(self.spotify_token)})
        
        print("Response should be 201 = " + str(response))
        
    
    # Call to refresh Spotify Authorisation Token.
    def call_refresh(self):
        print("• Refreshing Token.")

        refreshCaller = Refresh()
        self.spotify_token = refreshCaller.refresh()
        self.find_songs()

# This actually starts the program!
a = SaveSongs()
a.call_refresh()
