import os
import json
import requests
import time
from secrets import spotify_user_id
from refresh import Refresh

refreshCaller = Refresh()

os.system('cls')
print("[•_•] Playlist Grabber.")
print("Version 1.1.0: 07-MAR-17:10 (c) Viking Design.")
print("User: " + spotify_user_id)

class PlaylistGrab:
    def __init__(self):
        self.user_id = spotify_user_id
        self.spotify_token = ""
        self.playlist = ""
        self.here_i_am = os.path.dirname(os.path.abspath(__file__))
        self.more_than_fifty = 0
        
    def get_the_playlists(self):
        if self.more_than_fifty == 0:
            try:
                os.remove(self.here_i_am + "\Playlists - " + spotify_user_id + ".txt")
            except:
                pass
        params={"limit":50,"offset":self.more_than_fifty}
        query = "https://api.spotify.com/v1/users/{}/playlists".format(self.user_id)
        response = requests.request("get", url=query, headers={"Content-type": "application/json","Authorization":"Bearer {}".format(self.spotify_token)},params=params)
        response_json = response.json()

        File_object = open(self.here_i_am + r"\Playlists - " + spotify_user_id + ".txt","a")
        for i in response_json["items"]:
            self.name = (i["name"])
            self.total = (i["tracks"]["total"])
            self.uri = (i["uri"])
            check = (self.name[-3:])
            #print(check)
            if check == "0-9":
                File_object.writelines(["Playlist Name - " + str(self.name) + "\n" + str(self.uri) + "\n" + "Total Tracks - " + str(self.total) + "\n\n"])
        File_object.close()
        if self.more_than_fifty == 0:
            self.more_than_fifty = 50
            self.get_the_playlists()
        print("All Done")
        exit()

    def call_refresh(self):
        print("[•] Refreshing Token....")
        global refreshCaller
        while True:
            self.spotify_token = refreshCaller.refresh()
            if self.spotify_token == -1:
                print("[X] Error Refreshing Token - Retrying in 30 Secs [X]")
                time.sleep(30)
            else:
                break
        
a = PlaylistGrab()
a.call_refresh()
a.get_the_playlists()