import pandas as pd
import numpy as np
import spotipy
import requests
from spotipy import oauth2
import re

#===========================================================================================================================================
# go here: https://developer.spotify.com/dashboard/applications Make a new APP 
# and take the 3 bits of info for below. 
#============================================================================================================================================
SPOTIPY_CLIENT_ID = 'YOUR CLIENT ID'
SPOTIPY_CLIENT_SECRET = 'YOUR CLIENT SECRET'
SCOPE = ('user-read-recently-played,user-library-read,user-read-currently-playing,playlist-read-private,playlist-modify-private,playlist-modify-public,user-read-email,user-modify-playback-state,user-read-private,user-read-playback-state')
SPOTIPY_REDIRECT_URI = 'YOUR REDIRECT URI'
sp_oauth = oauth2.SpotifyOAuth(
    SPOTIPY_CLIENT_ID, SPOTIPY_CLIENT_SECRET, SPOTIPY_REDIRECT_URI, scope=SCOPE)

#click "AGREE" in your browser when the auth window pops up
#Then enter the web address of the next screen in the terminal window and hit return.....
code = sp_oauth.get_auth_response(open_browser=True)
sptoken = sp_oauth.get_access_token(code)
refresh_token = sptoken["refresh_token"]
sp = spotipy.Spotify(auth=sptoken["access_token"])
username = sp.current_user()["id"]

#=====================================================================================================================================

#create playlist and save playlist id
pl_name = 'myEndlessPlaylist1'
result = sp.user_playlist_create(username, name=pl_name)
pl_id = result['id']

#======================================================================================================================================

#ID for the public spotify playlist we're getting all the albums from
top_album_pl = '70n5zfYco8wG777Ua2LlNv'

#top_albums is list we'll use to make the top albums playlist
top_albums = []
offset = 0
while True:
    response = sp.playlist_items(top_album_pl,
                                 offset=offset)

    if len(response['items']) == 0:
        break
    top_albums += response['items']
    offset = offset + len(response['items'])

#===================================================================================================================================

#Here we make a DataFrame of all the top albums by looping through that list of response of dictionaries
album_df = []
for album in top_albums:
    
    track = album['track']['name']
    artist = album['track']['artists'][0]['name']
    album_name = album['track']['album']['name']
    track_id = album['track']['id']
    album_id = album['track']['album']['id']
    album_df.append([track,artist,album_name, track_id,album_id])
album_df = pd.DataFrame(album_df, columns =['track','artist','album','track_id','album_id'])

#====================================================================================================================================

#random seed so others can get the same album order as me
np.random.seed(10)

#make a DataFrame of all albums and add a random number between 0-1 "rand_key" for each album
all_albums = album_df.drop_duplicates('album_id').album_id
all_albums = pd.DataFrame(all_albums).reset_index(drop=True)
all_albums['rand_key'] = np.random.rand(len(all_albums))

#merge the albums DataFrame back with the full top albums DataFrame
album_df = pd.merge(album_df, all_albums, how='inner', on='album_id')

#sort by the rand_key (and by index so the songs within albums stay in order)
album_df['idx'] = album_df.index
album_df = album_df.sort_values(['rand_key', 'idx']).reset_index(drop=True)

#run the code below to exclude one-track albums
album_df_piv = pd.pivot_table(
    album_df, index='album_id', values='track_id', aggfunc='count')
album_df_piv.columns = ['num_tracks']
album_df = pd.merge(album_df, album_df_piv, how='left',
                    left_on='album_id', right_index=True)
album_df = album_df[album_df.num_tracks > 1].reset_index(drop=True)

album_df['idx'] = album_df.index

#do some data cleaning (getting rid of quotes, backslashes) so it will play nice
album_df.loc[(album_df['track'].str.contains('"')),
             'track'] = album_df.track.str.replace('"', '')
album_df.loc[(album_df['artist'].str.contains('"')),
             'artist'] = album_df.artist.str.replace('"', '')
album_df.loc[(album_df['album'].str.contains('"')),
             'album'] = album_df.album.str.replace('"', '')
album_df.loc[(album_df['track'].str.contains(r"\\")),
             'track'] = album_df.track.str.replace('\\', '')

#copy this album df to your clipboard to paste into google sheets or elsewhere.
album_df.to_clipboard(index=False)

#=================================================================================================================================

#initialize playlist of length 30
pl_length = 30
last_tracks_added = album_df.loc[0:pl_length-1]
tracks_to_add = last_tracks_added.track_id.tolist()
sp.playlist_add_items(pl_id,tracks_to_add )